Python - Sys Module

The sys module provides functions and variables used to manipulate different parts of the Python runtime environment. You will learn some of the important features of this module here.

sys.argv

sys.argv returns a list of command line arguments passed to a Python script. The item at index 0 in this list is always the name of the script. The rest of the arguments are stored at the subsequent indices.

Here is a Python script (test.py) consuming two arguments from the command line.

Example: test.py
import sys
print("Hello {}. Welcome to {} tutorial".format(sys.argv[1], sys.argv[2]))

This script is executed from command line as follows:

C:\python36> python test.py Martin Python Hello Martin. Welcome to Python tutorial

As you can see, sys.argv[1] contains the first parameter 'Martin', while sys.argv[2] contains the second parameter 'Python'. sys.argv[0] contains the script file name test.py.

sys.exit

This causes the script to exit back to either the Python console or the command prompt. This is generally used to safely exit from the program in case of generation of an exception.

sys.maxsize

Returns the largest integer a variable can take.

>>> import sys
>>>sys.maxsize
9223372036854775807

sys.path

This is an environment variable that is a search path for all Python modules.

>>>sys.path
['', 'C:\\python36\\Lib\\idlelib', 'C:\\python36\\python36.zip', 'C:\\python36\\DLLs', 'C:\\python36\\lib', 'C:\\python36', 'C:\\Users\\acer\\AppData\\Roaming\\Python\\Python36\\site-packages', 'C:\\python36\\lib\\site-packages']

sys.version

This attribute displays a string containing the version number of the current Python interpreter.

>>>sys.version
'3.7.0 (v3.7.0:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)]'

Learn more about the sys module in Python docs.