Python sys Module Tutorial

Python provides a built-in sys module in order to access some variables and functions used by the interpreter. Simply the sys module can be used to manipulate the current Python runtime and interpreter in order to change the Python scripts and applications execution environment. In the tutorial, we will use popular use cases for the sys module to read and change the Python scripts execution.

sys.argv (Passed Arguments)

Some arguments or parameters can be passed into the PYthon script. The sys.argv is used to store passed arguments and get them inside the Python script. The sys.argv is a list where every argument is stored as an item. The sys.argv[0] is used to store the current script name and all other items are an argument for the script.

import sys

print(sys.argv[0])

print(sys.argv[1])

print(sys.argv[2])

print(sys.argv[3])

This Python script is store with the test.py name and called with the following arguments.

./test.py usa germany turkey

The output is like below where the first item in the sys.argv list is the name of the script.

./test.py
 usa
 germany
 turkey

sys.exit (Exit)

A python script is executed via the Python interpreter. The script can exit after the execution is completed or exited explicitly by using the sys.exit.

import sys

print("This is a Python script")

sys.exit

print("This is a Python script")

sys.maxsize (Maximum Integer Size)

Python integer type is used to store numbers which can be used for different calculations. The maximum integer changes according to the Python version and operating system. The maximum integer size can be printed with the sys.maxsize.

import sys

print(sys.maxsize)

sys.path (Python Module Path)

Python interpreter uses different modules where these modules are located in different locations. These locations are called Python module path and this path information can be listed with the sys.path.

import sys

print(sys.path)
['', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/ismail/.local/lib/python3.8/site-packages', '/usr/local/lib/python3.8/dist-packages', '/usr/lib/python3/dist-packages']

sys.executable (Python Interpreter Executable Path)

Every Python script is executed via the Python interpreter executable. The current interpreter executable location can be displayed with the sys.executable.

import sys

print(sys.executable)

sys.version (Python Interpreter Version)

Python is a dynamic language that adds new features with new versions. The current interpreter version can be printed by using the sys.version variable like below.

import sys

print(sys.version)
3.8.6 (default, Jan 27 2021, 15:42:20) 
[GCC 10.2.0]

Leave a Comment