Python sys Module
FREE Online Courses: Click for Success, Learn for Free - Start Now!
sys is a powerful module that lets us access and alter various parts of the Python runtime environment. We can access several variables, constants, functions, and methods of the python interpreter. It is a built-in language and comes ready to use in the Python Standard Library. sys is a sub-module of the OS module.
Importing the sys Module in Python
We need to import the sys module using an import statement to use the functions that are available in the module. We can use the ‘import’ keyword to import the entire module or ‘from’ the keyword to import a specific function from the module. In our example, we use the import keyword.
Example of importing the sys module in Python
import sys print(dir(sys))
Output
In the above code example, we imported the sys module. We can also notice that we used the Python built-in function dir() to print all objects in the sys module. We can see that there are a number of objects in the sys module for us to play with. Let’s see what some of those objects do in Python.
Objects in sys Module
argv
The variable contains a list of command-line arguments and either name or path of the script we are running. The name or path of the script is always at index 0 and the arguments always start from index 1.
Example on using argv in Python
script import sys print(sys.argv)
Terminal
(apple) (base) MacBook-Pro:Geeks apple$ python main.py Python Geeks
Output
base_exec_prefix
It has the same value as base_prefix. Unlike base_prefix, it is much more efficient.
Example on using base_exec_prefix in Python
import sys print(sys.base_exec_prefix)
Output
base_prefix
It has the same value as prefix if we are not running a virtual environment. Unlike prefix, its value is set during Python startup.
Example on using base_prefix in Python
import sys print(sys.base_prefix)
Output
byteorder
It indicates the native byte order. It has different values depending on the platform. On big-endian, its value is a string “big” and on small-endian, its value is a string “little”.
Example on using byteorder in Python
import sys print(sys.byteorder)
Output
copyright
It is a string containing the copyright information of the Python version that we are currently using.
Example on using copyright in Python
import sys print(sys.copyright)
Output
All Rights Reserved.Copyright (c) 2000 BeOpen.com.
All Rights Reserved.Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.
Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved.
displayhook
It can be used to change the output behavior of an interactive python session. To do that, we have to assign a callable object which takes only a single argument to the displayhook.
Example on using displayhook in Python
import sys def func(n): print("the number is", n) sys.displayhook = func x = 4 x
Output
executable
It is a string containing the executable binary’s absolute path for the Python interpreter. Python either returns None or an empty string if it can’t find the path.
Example on using executable in Python
import sys print(sys.executable)
Output
exit([arg])
The function terminates the ongoing program. It can be used to exit the program and return to the command prompt or Python console. We can pass either a string or an integer to the function. Passing zero is considered to be a successful termination.
Example on using exit() in Python
import sys print(sys.exit())
Output
getdefaultencoding()
The function returns a string containing the default string encoding.
Example on using getdefaultencoding() in Python
import sys print(sys.getdefaultencoding())
Output
getrecursionlimit()
The function returns the current recursion limit of the Python interpreter.
Example on using getrecursionlimit() in Python
import sys print(sys.getrecursionlimit())
Output
getrefcount(object)
The function returns a reference count of the passed object. Python automatically deletes the memory of a variable when its reference count becomes zero.
Example on using getrefcount() in Python
import sys str = "PythonGeeks" print(sys.getrefcount(str))
Output
getswitcinterval()
The function returns the thread switch interval of the Python interpreter in seconds.
Example on using getswitchinterval() in Python
import sys print(sys.getswitchinterval())
Output
maxsize
The variable contains the highest Py_ssize_t value that can be stored. Its value depends on the CPU architecture.
Example on using maxsize in Python
import sys print(sys.maxsize)
Output on 32-bit architecture
Output on 64-bit architecture
modules
This variable contains a dictionary of all modules which are currently imported and their corresponding paths.
Example on using modules in Python
import sys import pandas print(sys.modules['pandas'])
Output
path
Whenever we try to import a module, Python has to search for that module. The variable path contains a list of paths that Python uses to search for the specified module.
Example on using path in Python
import sys print(sys.path)
Output
Projects/PythonGeeks, ‘/Users/apple/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/203.7148.72/PyCharm.app/Contents/plugins/python/helpers/pycharm_display’, ‘/usr/local/opt/[email protected]/Frameworks/Python.framework/Versions/3.8/lib/python38.zip’, ‘/usr/local/opt/[email protected]/Frameworks/Python.framework/Versions/3.8/lib/python3.8’, ‘/usr/local/opt/[email protected]/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload’, ‘/Users/apple/.local/share/virtualenvs/apple-kpxO2wBy/lib/python3.8/site-packages’, ‘/Users/apple/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/203.7148.72/PyCharm.app/Contents/plugins/python/helpers/pycharm_matplotlib_backend’]
platform
It is a string containing the name of the platform on which we are executing our Python files.
Example on using platform in Python
import sys print(sys.platform)
Output
prefix
It is a string containing the directory in which the platform-independent python files are installed.
Example on using prefix in Python
import sys print(sys.prefix)
Output
setrecursionlimit(limit)
The function is used to set a maximum number of recursions Python executes. Setting a limit to recursions prevents our program from overflowing the stack and ultimately crashing the program. It raises a RecursionError if we exceed the limit.
Example on using setrecursionlimit() in Python
import sys sys.setrecursionlimit(7) def recur(): return recur() recur()
Output
setswitchinterval(interval)
The function sets the thread switch interval of the Python interpreter in seconds.
Example on using setswitchinterval() in Python
import sys print(sys.getswitchinterval()) sys.setswitchinterval(1) print(sys.getswitchinterval())
Output
1.0
settrace(frame, event, arg)
The function logs the tracebacks of the Python interpreter.
Example on using settrace() in Python
import sys print("Code executed at line numbers") def func(*args): print(str(args[0].f_lineno), end="\t") def func1(): return None def func2(): return func1() sys.settrace(func) func2()
Output
10 7
stdin
The built-in file object contains real values of the stdin at the start of a program and used at finalization. Using this with functions like readline() allows us to take input from the user.
Example on using stdin in Python
import sys print("Your name is - ", sys.stdin.readline())
Input
sam
Output
stdout
stdout is a built-in file object that is used to display the output. We can use this to change the output behavior like redirecting output to a file rather than to a console.
Example on using stdout in Python
import sys sys.stdout.write("Python Geeks")
Output
Example on using stdout to redirect the output to a file in Python
import sys # saving the default output (console) for future use default_output = sys.stdout file = open('geeks.txt', 'w') sys.stdout = file # changing the output to file from console print("PythonGeeks") file.close() # Changing the output to console from file sys.stdout = default_output print("File Updated")
Output (Console)
File Updated
File
PythonGeeks
stderr
stderr is a built-in file object which displays exceptions. We can redirect exceptions to a file instead of a console with the help of stderr.
Example on using stderr in Python
import sys sys.stderr.write("Some Exception")
Output
Process finished with exit code 0
Example on using stderr to redirect exceptions to a file in Python
import sys # saving the default output (console) for future use console = sys.stderr file = open('geeks.txt', 'w') sys.stderr = file # changing the output to file from console sys.stderr.write("Exception raised 1") # Writing an exception file.close() # Changing the output to console from file sys.stderr = console sys.stderr.write("Exception raised 2") # Writing an exception
Output (Console)
Exception raised 2
File
Exception raised 1
version
The variable returns a string containing the Python interpreter’s current version.
Example on using version in Python
import sys print(sys.version)
Output
[Clang 11.0.3 (clang-1103.0.32.62)]
Python Interview Questions on the sys Module
Q1. The function in below has an infinite recursion. Add few lines to the existing code to prevent the function from calling itself more than 10 times.
Incomplete code
# Your code here def add_num(num): return add_num(num+num) add_num(1)
Ans 1. The completed code is as follows:
# Your code here import sys sys.setrecursionlimit(10) def add_num(num): return add_num(num+num) add_num(1)
Output
Q2. Write a program to input a word and print the first letter of that word without using the input() function.
Ans 2. Complete code is as follows:
import sys word = sys.stdin.readline() print(word[0])
Input
Hello
Output
Q3. Write a program to check the current version of Python. Print “Python2” if it less than 3 and print “Python3” if the version is 3 or greater than 3.
Ans 3. Complete code is as follows:
import sys if int(sys.version[0]) < 3: print("Python2") else: print("Python3")
Output
Q4. Write a program to print a variable without using the print() function.
Ans 4. Complete code is as follows:
import sys var = "Good days" sys.stdout.write(var)
Output
Q5. Write a program to input an integer and exit if the integer is 5, otherwise print the number.
Ans 5. Complete code is as follows:
import sys num = int(input()) if num == 5: sys.exit() else: print(num)
Input
5
Output
Quiz on Python sys Module
Conclusion
In this article, we learned about the sys module and ways of using the various functions and variables available in the module. Furthermore, please feel free to share them with us in the comment section if you have any queries.