Sitemap

PYTHON SYS MODULE

2 min readApr 2, 2024

--

Press enter or click to view image in full size

The sys module in Python provides information about the constants, functions, and methods of the Python interpreter. It allows you to access and modify some of the interpreter’s state and behavior.

These are the things you can do with the module:

COMMAND LINE ARGUMENTS

You can access command line arguments passed to your script using the `sys.argv` list. The first element of `sys.argv` is the name of the script, and the rest are the arguments.


import sys
print("Number of arguments: ", len(sys.argv))
print("Argument List: ", str(sys.argv))

Exit the Program

You can exit the program using the `sys.exit()` function. This function takes an optional argument which is the exit status.

import sys
sys.exit("Goodbye, cruel world!")

Get the Current Module

You can get the current module using the `sys.modules[__name__]` expression.


import sys
current_module = sys.modules[__name__]
print(current_module)

Get the Platform

You can get the platform (operating system) using the `sys.platform` attribute.


import sys
print(sys.platform)

Get the Python Version

You can get the Python version using the `sys.version` attribute.


import sys
print(sys.version)

Set the Standard Input, Output, and Error Streams

You can set the standard input, output, and error streams using the `sys.stdin`, `sys.stdout`, and `sys.stderr` attributes.


import sys
sys.stdout.write("Hello, world!\n")

Add a Path to the Module Search Path

You can add a path to the module search path using the `sys.path.append()` method.


import sys
sys.path.append("/path/to/directory")

Get the Maximum Recursion Depth

Get kipngeno koech’s stories in your inbox

Join Medium for free to get updates from this writer.

You can get the maximum recursion depth using the `sys.getrecursionlimit()` function.


import sys
print(sys.getrecursionlimit())

Set the Maximum Recursion Depth

You can set the maximum recursion depth using the `sys.setrecursionlimit()` function.


import sys
sys.setrecursionlimit(1000)

These are just a few examples of what you can do with the sys module. The sys module provides many other functions and attributes that you can use to interact with the Python interpreter.

--

--

kipngeno koech
kipngeno koech

Written by kipngeno koech

You will find me here, lost in words, for it is my pen that listens and understands the depths of my soul.