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:
Python
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.
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.
Python
import sys
for line in sys.stdin:
if 'q' == line.rstrip():
break
print(f'Input : {line}')
print("Exit")
Output
Using sys.stdin()2. sys.stdout: Writes output to the standard output stream and allows low-level control over printed output.
Python
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
Python
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.
Python
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
Using sys.argv()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.
Python
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
Python
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
Python
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:
Python
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:
Python
import sys
a = 'Geeks'
print(sys.getrefcount(a))
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.
|
Similar Reads
Python Modules Python Module is a file that contains built-in functions, classes,its and variables. There are many Python modules, each with its specific work.In this article, we will cover all about Python modules, such as How to create our own simple module, Import Python modules, From statements in Python, we c
7 min read
Python Arrays Lists in Python are the most flexible and commonly used data structure for sequential storage. They are similar to arrays in other languages but with several key differences:Dynamic Typing: Python lists can hold elements of different types in the same list. We can have an integer, a string and even
9 min read
asyncio in Python Asyncio is a Python library that is used for concurrent programming, including the use of async iterator in Python. It is not multi-threading or multi-processing. Asyncio is used as a foundation for multiple Python asynchronous frameworks that provide high-performance network and web servers, databa
4 min read
Calendar in Python Python has a built-in Python Calendar module to work with date-related tasks. Using the module, we can display a particular month as well as the whole calendar of a year. In this article, we will see how to print a calendar month and year using Python. Calendar in Python ExampleInput: yy = 2023 mm =
2 min read
Python Collections Module The collection Module in Python provides different types of containers. A Container is an object that is used to store different objects and provide a way to access the contained objects and iterate over them. Some of the built-in containers are Tuple, List, Dictionary, etc. In this article, we will
12 min read
Working with csv files in Python Python is one of the important fields for data scientists and many programmers to handle a variety of data. CSV (Comma-Separated Values) is one of the prevalent and accessible file formats for storing and exchanging tabular data. In article explains What is CSV. Working with CSV files in Python, Rea
10 min read
Python datetime module In Python, date and time are not data types of their own, but a module named DateTime in Python can be imported to work with the date as well as time. Python Datetime module comes built into Python, so there is no need to install it externally. In this article, we will explore How DateTime in Python
14 min read
Functools module in Python The functools module offers a collection of tools that simplify working with functions and callable objects. It includes utilities to modify, extend, or optimize functions without rewriting their core logic, helping you write cleaner and more efficient code.Let's discuss them in detail.1. Partial cl
5 min read
hashlib module in Python A Cryptographic hash function is a function that takes in input data and produces a statistically unique output, which is unique to that particular set of data. The hash is a fixed-length byte stream used to ensure the integrity of the data. In this article, you will learn to use the hashlib module
5 min read
Heap queue or heapq in Python A heap queue or priority queue is a data structure that allows us to quickly access the smallest (min-heap) or largest (max-heap) element. A heap is typically implemented as a binary tree, where each parent node's value is smaller (for a min-heap) or larger (for a max-heap) than its children. Howeve
7 min read