How to use Sys Module in Python

Python sys module is the built-in module that provides various functions and variables that are used to manipulate different parts of the Python runtime environment. These variables and functions can be controlled by the interpreter at run time and it is always available.

sys module allows accessing system-specific parameters and functions. Let’s discuss the important functions here in this tutorial provided by the sys module.

 

Functions of Python sys Module

You can simply call the sys module in your program as:

import sys

Note: Throughout the example, we discuss here contains this module imported. So make sure to import this module if it is missed in the example.

 

sys.version

This attribute returns a string containing the version number of the Python interpreter plus additional information on the build number and compiler used.

>>> sys.version
'3.8.10 (default, Nov 26 2021, 20:14:08) \n[GCC 9.3.0]'

 

sys.version_info

This attribute returns a tuple containing the five components of the version number: major, minor, micro, releaselevel, and serial.

>>> sys.version_info
sys.version_info(major=3, minor=8, micro=10, releaselevel='final', serial=0)
>>>

This attribute is used to extract the version of the Python interpreter being used during runtime. You can access individual components by name or index number.

>>> sys.version_info[0]
3
>>> sys.version_info.major
3
>>>

 

sys.platform

This attribute returns a string containing the platform identifier that can be used to code the program based on the platform. In short, this helps run the program irrespective of the platform.

>>> sys.platform
'linux'
>>>

To run the program based on different platforms

if sys.platform.startswith(‘win32’):
    # Windows code here...
elif sys.platform.startswith('linux'):
    # Linux-specific code here...
elif sys.platform.startswith(‘darwin’):
    # macOS code here...

 

sys.exit

This function is used to safely exit from the program whenever any exceptions are raised in the code. To demonstrate its use case, you can simply call this function in Python prompt which results in exiting the interpreter.

>>> sys.exit()
pythonsansar@pythonsansar:~$

 

sys.argv

This returns a list of command-line arguments passed to a Python script. sys.argv[0] gives the name of the Python script.

Example

Let’s create an add.py module that adds all the numbers pass as command-line arguments with the help of sys.argv

add.py

import sys


# list containing all the values
values = sys.argv

def add_number(numbers):
    script_name = numbers.pop(0)
    sum = 0
    # make sure to neglect index 0
    for number in numbers:
        sum += int(number) # by default str
    print(f'The name of the Python script is: {script_name}')
    print(f"The sum of all the numbers in the list:{numbers} is {sum}")


# call function
add_number(values)

Execute the script as:

pythonsansar@pythonsansar:~$  python3 add.py 1 2 3 4 5

Output:

The name of the Python script is: add.py
The sum of all the numbers in the list:['1', '2', '3', '4', '5'] is 15

 

sys.modules

This variable returns the dictionary that maps existing python module names to modules that have already been loaded.

>>> sys.modules
{'sys': <module 'sys' (built-in)>, 'builtins': <module 'builtins' (built-in)>, '_frozen_importlib': <module 'importlib._bootstrap' (frozen)>, '_imp': <module '_imp' (built-in)>, '_warnings': <module '_warnings' (built-in)>,......}

Note: In the above output, I have truncated other modules as it very large in size.

 

sys.builtin_module_names

This variable returns a tuple of strings containing the names of all modules that are built-in into the Python interpreter.

>>> sys.builtin_module_names
('_abc', '_ast', '_bisect', '_blake2', '_codecs', '_collections', '_csv', '_datetime', '_elementtree', '_functools', '_heapq', '_imp', '_io', '_locale', '_md5', '_operator', '_pickle', '_posixsubprocess', '_random', '_sha1', '_sha256', '_sha3', '_sha512', '_signal', '_socket', '_sre', '_stat', '_statistics', '_string', '_struct', '_symtable', '_thread', '_tracemalloc', '_warnings', '_weakref', 'array', 'atexit', 'binascii', 'builtins', 'cmath', 'errno', 'faulthandler', 'fcntl', 'gc', 'grp', 'itertools', 'marshal', 'math', 'posix', 'pwd', 'pyexpat', 'select', 'spwd', 'sys', 'syslog', 'time', 'unicodedata', 'xxsubtype', 'zlib')
>>>

Count the built-in methods in Python

>>> len(sys.builtin_module_names)
59
>>>

We can also say there are altogether 59 built-in modules in Python.

 

sys.executable

This attribute returns the string that contains the absolute path of the executable binary file for the Python interpreter. If there is no such executable binary file for the interpreter,  it will return an empty string or None.

>>> sys.executable
'/usr/bin/python3'
>>>

Right now on my Linux machine, Python interpreter absolute path is '/usr/bin/python3'.

Leave a Comment