Python sys Module – Important Functions
Don't become Obsolete & get a Pink Slip
Follow DataFlair on Google News & Stay ahead of the game
1. Objective
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.
2. 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:
You must take a look of Python os Module
>>> import sys #Get version information >>> sys.version
‘3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)]’
>>> sys.version_info
sys.version_info(major=3, minor=7, micro=0, releaselevel=’final’, serial=0)
>>> sys.getrecursionlimit() #Get maximal recursion depth
1000
>>> sys.setrecursionlimit(1500) #Set maximal recursion depth >>> sys.getrecursionlimit()
1500
Let’s revise CGI Programming in Python with functions
3. 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])
C:\Users\Ayushi\Desktop>py sysdemo.py 2 3
[‘sysdemo.py’,’2’,’3’]
The function is sysdemo.py
Argument:2
Argument:3
4. 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.
Let’s revise Python Zipfile
>>> import sys >>> x=42 >>> x
42
>>> print(x)
42
>>> def show(x): print("Output:",x) >>> sys.displayhook=show >>> x
Output: 42
>>> print(x)
42
Output: None
5. Ways to Read and Write in Python sys Module
We can also use the readline() method to get input from the user:
Do you know about Python array Module
>>> print("Type in value: ",sys.stdin.readline()[:-1]) 23
Type in value: 23
The following piece of code lets us print to the screen:
>>> sys.stdout.write('Way to write')
Way to write12
>>> sys.stdout.write('Way to write\n')
Way to write
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.
6. 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
7. 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.
You must read about Python Packages
>>> sys.path
[”, ‘C:\\Users\\Ayushi\\AppData\\Local\\Programs\\Python\\Python37-32\\Lib\\idlelib’, ‘C:\\Users\\Ayushi\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip’, ‘C:\\Users\\Ayushi\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs’, ‘C:\\Users\\Ayushi\\AppData\\Local\\Programs\\Python\\Python37-32\\lib’, ‘C:\\Users\\Ayushi\\AppData\\Local\\Programs\\Python\\Python37-32’, ‘C:\\Users\\Ayushi\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages’, ‘C:\\Users\\Ayushi\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\scrapy-1.5.1-py3.7.egg’, ‘C:\\Users\\Ayushi\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\service_identity-17.0.0-py3.7.egg’, ‘C:\\Users\\Ayushi\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\parsel-1.5.0-py3.7.egg’]
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.
Have a look at Python Modules vs Packages
8. 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.
Let’s revise the Python Datetime Module
9. 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
10. 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.
Have a look at the Python Multiprocessing Module
>>> a=7 >>> sys.getrefcount(a)
37
To get the name of the platform we’re running Python on, we make a call to sys.platform in Python:
>>> sys.platform
‘win32’
11. 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
Hello
Let’s revise deep and shallow copy in Python
>>> saveout=sys.stdout >>> fsock=open('out.log','w') >>> sys.stdout=fsock >>> print('Message to log') >>> sys.stdout=saveout >>> fsock.close()
12. 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).
Read – Python Assert Statements
Another way we use sys.stderr is as follows:
>>> for i in range(3): sys.stderr.write('Hello')
Hello5
Hello5
Hello5
Unlike stdout, stderr does not add carriage returns.
A similar function flush() lets us flush write buffers.
13. 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.
Let’s discuss Python Unit Testing
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.
14. Conclusion – sys Module in Python
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. Still, if you have any doubt regarding Python sys Module, ask in the comment tab.
See also –
Python Collection Module
For reference