Python sys Module – Important Functions
Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python
In our last Python tutorial, we discussed Python Subprocess. Today, we will discuss Python sys Module.Â
Moreover, we learn about functions like version, displayhook, stderr, and more. Also, we will see how to import sys in Python.Â
So, let’s start the Python sys Module tutorial.
What is Python sys Module?
Let’s get to know it first. The sys module in Python lets us access system-specific parameters and functions.
It gives us information about constants, functions, and methods of the interpreter.
To find out more about it, you can try one of two functions:
- Summarized information- constants, functions, methods:
>>> dir(sys)
- Detailed information-
>>> help(sys)
Some things you can do with it are:
>>> import sys #Get version information >>> sys.version
Output
>>> sys.version_info
Output
>>> sys.getrecursionlimit() #Get maximal recursion depth
Output
>>> sys.setrecursionlimit(1500) #Set maximal recursion depth >>> sys.getrecursionlimit()
Output
Command-line Arguments in Python sys Module
We can store the command-line arguments we pass to a script in a list we call sys.argv.
The first item of this is the name of the script; the arguments are next.
Save the following code in a script:
import sys print(sys.argv) for i in range(len(sys.argv)): if i==0: print("The function is",sys.argv[0]) else: print("Argument:",sys.argv[i])
Output
[‘sysdemo.py’,’2’,’3’]
The function is sysdemo.py
Argument:2
Argument:3
Changing the Output Behavior of the Shell
We’ve so often used the Python shell interactively and even as a calculator. But what if we wanted to change how it delivers the output?
Well, we can; we simply rebind sys.displayhook to a callable object.
>>> import sys >>> x=42 >>> x
Output
>>> print(x)
Output
>>> def show(x): print("Output:",x) >>> sys.displayhook=show >>> x
Output
>>> print(x)
Output
Ways to Read and Write in Python sys Module
We can also use the readline() method to get input from the user:
>>> print("Type in value: ",sys.stdin.readline()[:-1]) 23
Output
The following piece of code lets us print to the screen:
>>> sys.stdout.write('Way to write')
Output
>>> sys.stdout.write('Way to write\n')
Output
13
Notice that it gives us the number of characters, which is why it gives us 13 instead of 12 when we give it a \n newline character too at the end.
Getting Names of Modules
sys.modules in Python gives us a dictionary of the names of the modules existing in the current shell.
>>> import sys >>> sys.modules
Investigating the Path in Python sys Module
sys.path in Python will give you a list of paths it will search in whenever you make an import.
>>> sys.path
Output
You can add a path to this with the append() method-
>>> sys.path.append('C:\\Users\\Ayushi\\Desktop')
Now, when you make a call to sys.path in Python, you can see this location in the list.
Getting the Copyrights in Python sys Module
sys.copyright in Python displays the copyright information on the currently-installed version of Python.
>>> print(sys.copyright)
Copyright (c) 2001-2018 Python Software Foundation.
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.
Exiting Current Flow of Execution in Python sys Module
sys.exit in Python lets the interpreter abruptly exit the current flow of execution.
>>> sys.exit
You can use a try-except block to catch this call-
>>> try: sys.exit(1) except SystemExit: pass
Getting Reference Count and Platform
The getrefcount function gives us the count of references to an object where used.
When in a program, this value drops to 0, Python cleans up the memory for this variable. Let’s take an example.
>>> a=7 >>> sys.getrefcount(a)
Output
To get the name of the platform we’re running Python on, we make a call to sys.platform in Python:
>>> sys.platform
Output
Redirecting Output in Python sys Module
Instead of delivering the output to the console, you can log into a text file.
>>> import sys >>> print('Hello') #Prints normally
Output
>>> saveout=sys.stdout >>> fsock=open('out.log','w') >>> sys.stdout=fsock >>> print('Message to log') >>> sys.stdout=saveout >>> fsock.close()
Redirecting Error Information in Python sys Module
Using sys.stderr and a text file in Python, we can log error information to the text file. See how:
>>> import sys >>> fsock=open('error.log','w') #Opening the file >>> sys.stderr=fsock #Redirecting standard error by assigning file object of file to stderr >>> raise Exception('this is an error') >>> fsock.close()
Note that this traceback doesn’t show up in the log file until we close its file object in Python (which, in this case, is fsock).
Another way we use sys.stderr is as follows:
>>> for i in range(3): sys.stderr.write('Hello')
Output
Hello5
Hello5
Unlike stdout, stderr does not add carriage returns.
A similar function flush() lets us flush write buffers.
More Functions in Python sys Module
The purpose of this tutorial is to get you started with the sys module; there is so much more to it.
To get a list of all the built-in functions and methods we have for sys, try the calling the dir() function on it.
Try them out, won’t you?
So, this was all in Python sys Module. Hope you like our explanation.
Python Interview Questions on sys module
- What is sys module in Python?
- What is the most common use of Python sys library?
- What is Python sys argv?
- What is OS and SYS in Python?
- What is Python SYS Path?
Conclusion
Hence, today in this Python sys module tutorial, we took a brief look at various functions and methods available with the Python sys module, including argv, stdin, stdout, stderr, setrecursionlimit, and exit.
We also discussed the meaning of import sys in Python.
If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google