Table of contents
1.
Introduction
2.
What is sys module?
3.
Command Line arguments with sys
4.
I/O operations with sys
4.1.
sys.stdin
4.2.
sys.stdout
4.3.
sys.stderr
5.
sys.getrefcount() 
6.
sys.exc_clear()
7.
sys.setrecursionlimit(limit)
8.
sys.path() 
9.
sys.exit(code) 
10.
Variables in the sys Module
11.
Functions in the sys Module
12.
Frequently Asked Questions
12.1.
What is the sys library in Python?
12.2.
What is sys.platform in Python?
12.3.
What is the SYS version of Python?
13.
Conclusion
Last Updated: Nov 20, 2024
Easy

Sys Module in Python

Author APURV RATHORE
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

These days, Python is a prevalent and sophisticated scripting language. Python is becoming increasingly popular in various fields, including application development, website development, and the creation of analytical products and production-level code. One of the reasons for this is the flexibility and ease of usage of the modules. Let's take a look at one of Python's most popular modules, "Sys." Sys module essentially defines the surroundings. 

We will learn more about the sys module in this article. 

sys Module

Recommended Topic, Floor Division in Python and Convert String to List Python.

What is sys module?

The sys module in Python contains several methods and variables for manipulating various aspects of the Python runtime environment. It helps you work with the interpreter since it gives you access to variables and functions that work closely with it.

For example, if we want to get the Python interpreter version, we can use the following command. 

import sys
print(sys.version)
You can also try this code with Online Python Compiler
Run Code

Output:

3.9.10 (tags/v3.9.10:f2f3f53, Jan 17 2022, 15:14:21) [MSC v.1929 64 bit (AMD64)]

 

Along with the version (3.9.10 in my case), it also provides additional information about the system and interpreter. 

Command Line arguments with sys

The parameters sent together with the calling statement during the program's execution are known as command-line arguments. The sys module exposes a variable named sys.argv that may be used to do this using the sys module.

sys.argv provides a list of the command line arguments. The first element of the sys.argv list is the name of the current Python program. 

import sys
 
print("The number of arguments passed: ",len(sys.argv))

print("The arguments passed to the file: ",*sys.argv)

print("The name of the python file: ",sys.argv[0])

curSum = 0
for i in range(1,len(sys.argv)):
    print("The",i,"th argument is",sys.argv[i])
    curSum += int(sys.argv[i])

print(curSum)
You can also try this code with Online Python Compiler
Run Code

 

Output:

PS D:\Course\Codeforces> python main.py 9 10
The number of arguments passed:  3
The arguments passed to the file:  main.py 9 10
The name of the python file:  main.py
The 1 th argument is 9
The 2 th argument is 10
19

 

Recommended Topic: Fibonacci Series in Python

I/O operations with sys

Variables in the sys modules provide for better control of input and output. We can even send input and output to different devices.

The following variables are used to control input and output: sys.stdin, sys.stdout, and sys.stderr. 

sys.stdin

stdin refers to a stream from which the application takes its input data. This function is significantly different from the input() in that it reads the user's escape character as well. 

import sys
print("Enter name")
inp = sys.stdin.readline()
print("your name is ",inp)
You can also try this code with Online Python Compiler
Run Code

 

Output:

Enter name
Apurv
your name is  Apurv

sys.stdout

The interpreter's standard output stream in Python is equivalent to this built-in file object. The stdout command is used to send output to the screen console. The output from a print statement, an expression statement, or even a prompt straight for input might take many different forms. Streams are set to text mode by default. In reality, whenever a print function is used in the code, it is printed first to sys.stdout, then to the screen.

import sys 
sys.stdout.write("Hello Ninjas")
You can also try this code with Online Python Compiler
Run Code

Output:

 

Hello Ninjas

sys.stderr

The error message is prompted using sys.stderr when an exception occurs. 

sys.getrefcount() 

To retrieve the reference count for any object, use the sys.getrefcount() function. Python uses this value because when it equals 0, the memory for that particular value is destroyed.

 

import sys
 
var = "20"
print(sys.getrefcount(var))
You can also try this code with Online Python Compiler
Run Code

 

Output:

4

 

You can compile it with online python compiler.

sys.exc_clear()

This method allows you to delete any data associated with current or past exceptions. When you need to free up allocated resources and perform object finalisation, this method comes in handy.

sys.setrecursionlimit(limit)

This function can be used to restrict the Python interpreter's maximum depth. It assists you in maintaining a stopover endless recursion, which can lead to overflow. The largest possible limit, on the other hand, varies from platform to platform. If someone sets the limit higher, they should be aware of the danger of crashes in Python.

sys.path() 

The sys module's built-in variable sys.path delivers a list of directories where the interpreter will look for the needed module.

When a module is imported into a Python file, the interpreter looks for it among the interpreter's built-in modules first. It searches the list of directories defined by sys.path if none are found.

import sys
print(sys.path)
You can also try this code with Online Python Compiler
Run Code

 

Output:

['C:\\Users\\apurv\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0', 'C:\\Users\\apurv\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python39\\site-packages']

Check out this article - String slicing in Python

sys.exit(code) 

sys.exit() can be used to exit the program. An optional parameter can be passed to the function indicating the status of the termination. 0 indicates successful execution.

import sys
 
a = 10
b = 0

if b==0:
    sys.exit("Error, second number is 0")
else:
    print("The result is",a/b)
You can also try this code with Online Python Compiler
Run Code

 

Output:

Error, second number is 0

 

Also see, How to Check Python Version in CMD

Variables in the sys Module

VariableExplanation
sys.argvList of command-line arguments passed to the script. The first element is the script name.
sys.byteorderIndicates the byte order of the host platform ('little' or 'big').
sys.builtin_module_namesTuple of all built-in module names compiled into the Python interpreter.
sys.platformString indicating the platform the Python interpreter is running on (e.g., 'win32', 'linux').
sys.versionString containing the Python version number and additional details.
sys.version_infoTuple containing the major, minor, micro, release level, and serial of the Python version.
sys.modulesDictionary mapping module names to loaded module objects.
sys.pathList of strings specifying the search paths for module imports.
sys.maxsizeMaximum value of a Python integer, platform-dependent (usually 231−12^{31}-1231−1 or 263−12^{63}-1263−1).
sys.stdinFile object corresponding to standard input (readable).
sys.stdoutFile object corresponding to standard output (writable).
sys.stderrFile object corresponding to standard error output (writable).
sys.flagsFlags for the Python interpreter, such as debug, interactive, etc.
sys.executablePath to the Python interpreter binary.
sys.getdefaultencodingReturns the default string encoding used by Python.

Functions in the sys Module

FunctionExplanation
sys.exit([arg])Exits the Python interpreter with the specified status (0 for success, nonzero for errors).
sys.getsizeof(object)Returns the size (in bytes) of an object in memory.
sys.getrecursionlimit()Returns the current maximum recursion depth limit.
sys.setrecursionlimit(limit)Sets a new maximum recursion depth limit.
sys.getrefcount(object)Returns the reference count for an object (may be higher than expected).
sys.is_finalizing()Checks if the interpreter is shutting down.
sys.modules.clear()Clears the sys.modules dictionary (use with caution).
sys.platformReturns the name of the operating system platform.
sys.exc_info()Returns information about the current exception being handled.
sys.stdout.write(string)Writes a string to standard output.
sys.stdin.read()Reads input from standard input.
sys.settrace(tracefunc)Sets a trace function for debugging or profiling.
sys.getwindowsversion()Returns version info for Windows (only available on Windows).
sys.getfilesystemencoding()Returns the encoding used by the file system to encode/decode file names.

Frequently Asked Questions

What is the sys library in Python?

The sys library in Python provides functions and variables to interact with the Python interpreter and its runtime environment.

What is sys.platform in Python?

sys.platform is a string that identifies the platform (e.g., 'win32', 'linux', 'darwin') the Python interpreter is running on.

What is the SYS version of Python?

sys.version is a string providing the Python version and build information, such as the version number, build date, and compiler used.

Conclusion

In this article, we have discussed the Sys Module in Python. The sys module is a powerful tool for interacting with the Python interpreter and its runtime environment. From accessing command-line arguments to retrieving system-specific information, it provides essential functionality for writing flexible and platform-aware programs. Whether you're managing script execution, analyzing memory usage, or debugging, the sys module equips you with the tools to dive deep into the Python runtime.

Live masterclass