Sys Module
sys module provides access to variables and functions that
interact closely with Python interpreter and runtime
environment. It allows developers to manipulate various
aspects of program execution and interpreter itself.
Example
import sys
print([Link])
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.
Why do we need sys module?
1. Gives access to system-specific parameters and functions like
command-line arguments.
2. Allows interaction with Python runtime environment (e.g., path,
version, exit).
3. Useful for reading input and writing output using [Link] and
[Link].
4. Enables control over the interpreter with functions like [Link]()
and [Link]().
5. Helps in debugging and managing system-level behavior in
Python scripts.
The sys module controls program input, output and error streams, enabling
precise data handling beyond standard input and print functions.
1. [Link]:
Reads input directly from the standard input stream and supports reading
multiple lines or redirected input.
import sys
for line in [Link]:
if 'q' == [Link]():
break
print(f'Input : {line}')
print("Exit")
2. [Link]:
Writes output to the standard output stream and allows low-level control
over printed output.
import sys
[Link](‘This is python’)
3. [Link]:
Writes messages to the standard error stream and separates error messages
from regular output
import sys
def fun(*args):
print(*args, file=[Link])
fun("Hello World")
Note: The output of this code will be "Hello World" but it appears under "Runtime Errors"
because [Link] sends the message to the error stream, not the regular 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
[Link]. It's main purpose are:
1. It is a list of command-line arguments.
2. len([Link]) provides the number of command-line arguments.
import sys
n = len([Link])
print("Total arguments passed:", n)
print("Name of Python script:", [Link][0])
print("Arguments passed:", end=" ")
for i in range(1, n):
print([Link][i], end=" ")
Sum = 0
for i in range(1, n):
Sum += int([Link][i])
print(Sum)
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
[Link]([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 [Link]() method.
import sys
age = 17
if age < 18:
[Link]("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 [Link]() 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
[Link] 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: [Link] is an ordinary list and can be manipulated.
Example 1: Listing all paths
import sys
print([Link])
Explanation: This code will print the system paths that Python uses to search for
modules. The [Link] list contains the directories that Python will search for modules
when it imports them.
Working with Modules
[Link] 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: [Link] is an ordinary list and can be manipulated.
Example 2: Truncating [Link]
import sys
[Link] = []
import pandas
Output
ModuleNotFoundError: No module named 'pandas'
Explanation: This code will raise an error because the pandas module
cannot be found if [Link] is emptied. By setting [Link] to an empty list,
Python is prevented from locating any modules outside built-ins.
[Link]()
[Link] 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([Link])
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
[Link]() 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 = ‘abc'
print([Link](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
[Link]()
[Link]() method is used to set the maximum depth of the Python interpreter
stack to the required limit.
[Link]() method is used to find the current recursion limit of the interpreter or
[Link]()
to find the maximum depth of the Python interpreter stack.
It is used for implementing debuggers, profilers and coverage tools. This is thread-specific and
[Link]() must register the trace using [Link](). On a higher level, [Link]() registers the
traceback to the Python interpreter
[Link]() method is used to set the interpreter’s thread switch interval (in
[Link]()
seconds).
[Link]() It fetches the largest value a variable of data type Py_ssize_t can store.
[Link] maxint/INT_MAX denotes the highest value that can be represented by an integer.
[Link]() method is used to get the current default string encoding used by the
[Link]()
Unicode implementation.
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]