Python sys Module
The sys module in Python provides access to variables and functions that interact closely with the Python interpreter and runtime environment. It allows developers to manipulate various aspects of program execution and the interpreter itself. It's Key capabilities include:
- Accessing command-line arguments.
- Fetching the Python interpreter version.
- Redirecting input/output streams, such as sys.stdin, sys.stdout and sys.stderr.
- Exiting the program gracefully.
- Handling exceptions and configuring interpreter settings.
Example:
import sys
print(sys.version)
Output
3.6.9 (default, Oct 8 2020, 12:12:24)
[GCC 8.4.0]
Explanation: This code prints the version of the Python interpreter currently in use, which helps in identifying compatibility and environment details.
Input and Output using Python sys
The sys module controls program input, output, and error streams, enabling precise data handling beyond standard input and print functions.
1. sys.stdin: Reads input directly from the standard input stream and supports reading multiple lines or redirected input.
import sys
for line in sys.stdin:
if 'q' == line.rstrip():
break
print(f'Input : {line}')
print("Exit")
Output

2. sys.stdout: Writes output to the standard output stream and allows low-level control over printed output.
import sys
sys.stdout.write('Geeks')
Output
Geeks
3. sys.stderr: Writes messages to the standard error stream and separates error messages from regular output
import sys
def fun(*args):
print(*args, file=sys.stderr)
fun("Hello World")
Output

Command-Line Arguments
Command-line arguments are those which are passed during the calling of the program along with the calling statement. To achieve this using the sys module, the sys module provides a variable called sys.argv. It's main purpose are:
- It is a list of command-line arguments.
- len(sys.argv) provides the number of command-line arguments.
import sys
n = len(sys.argv)
print("Total arguments passed:", n)
print("Name of Python script:", sys.argv[0])
print("Arguments passed:", end=" ")
for i in range(1, n):
print(sys.argv[i], end=" ")
Sum = 0
for i in range(1, n):
Sum += int(sys.argv[i])
print(Sum)
Output

Explanation: This code sums the command-line arguments passed to the script by converting each to an integer and adding them up using the sys module.
Exiting the Program
sys.exit([arg]) can be used to exit the program. The optional argument arg can be an integer giving the exit or another type of object. If it is an integer, zero is considered "successful termination".
Note: A string can also be passed to the sys.exit() method.
import sys
age = 17
if age < 18:
sys.exit("Age less than 18")
else:
print("Age is not less than 18")
Output
An exception has occurred, use %tb to see the full traceback.
SystemExit: Age less than 18
Explanation: This code uses sys.exit() to terminate the program if age is less than 18, displaying a message otherwise, it prints that the age is not less than 18.
Working with Modules
sys.path is a list in the sys module that defines directories Python searches for modules after checking built-ins. As a regular list, it can be modified at runtime to add, remove or reorder paths.
Note: sys.path is an ordinary list and can be manipulated.
Example 1: Listing all paths
import sys
print(sys.path)
Output

Explanation: This code will print the system paths that Python uses to search for modules. The sys.path list contains the directories that Python will search for modules when it imports them.
Example 2: Truncating sys.path
import sys
sys.path = []
import pandas
Output
ModuleNotFoundError: No module named 'pandas'
Explanation: This code will raise an error because the pandas module cannot be found if sys.path is emptied. By setting sys.path to an empty list, Python is prevented from locating any modules outside built-ins.
sys.modules()
sys.modules is a dictionary that contains all the modules currently imported in the Python interpreter. The keys are module names, and the values are the corresponding module objects. Example:
import sys
print(sys.modules)
Output

Explanation: This code will print a dictionary of all the modules that have been imported by the current Python interpreter. The dictionary keys are the module names, and the dictionary values are the module objects.
Reference Count
sys.getrefcount() method is used to get the reference count for any given object. This value is used by Python as when this value becomes 0, the memory for that particular value is deleted. Example:
import sys
a = 'Geeks'
print(sys.getrefcount(a))
Output
4
Explanation:This code prints the reference count of the object a, which indicates how many times it is referenced. When the count reaches 0, the object is no longer used and is garbage collected.
More Functions in Python sys
Function | Description |
---|---|
sys.setrecursionlimit() | sys.setrecursionlimit() method is used to set the maximum depth of the Python interpreter stack to the required limit. |
sys.getrecursionlimit() method | sys.getrecursionlimit() method is used to find the current recursion limit of the interpreter or to find the maximum depth of the Python interpreter stack. |
sys.settrace() | It is used for implementing debuggers, profilers and coverage tools. This is thread-specific and must register the trace using threading.settrace(). On a higher level, sys.settrace() registers the traceback to the Python interpreter |
sys.setswitchinterval() method | sys.setswitchinterval() method is used to set the interpreter’s thread switch interval (in seconds). |
sys.maxsize() | It fetches the largest value a variable of data type Py_ssize_t can store. |
sys.maxint | maxint/INT_MAX denotes the highest value that can be represented by an integer. |
sys.getdefaultencoding() method | sys.getdefaultencoding() method is used to get the current default string encoding used by the Unicode implementation. |