Introduction to Python Sys Module
Python is a very popular and powerful scripting language these days. From developing application to developing websites, making analytical product to production level codes, python getting so much popularity. One of the reasons behind are its flexibility, easy to use modules. Let’s see one of the widely used module in python known as “Sys”. “Sys” module is defined for system. It defines basically, the environment. In order to import sys module, one can simply type in “import sys”.
Functions of Python Sys Module
Given below are the functions of Python Sys Module:
Let’s import sys module in our IDE and check the version of python.
1. version
It helps you understand the version of python being in use.
Code:
import sys
sys.version
Output:
2. executable
It’s a string that tells you where your filesystem or your python interpreter exists.
Code:
import sys
sys.executable
Output:
3. sys.builtin_module_names
This helps you understand which all are the built-in modules available in python. One need not to download these modules, and hence can directly be used environment after importing.
Code:
sys.builtin_module_names
Output:
Like shown here:
However the modules which are not part of sys needs to be first downloaded and then imported in python environment.
Examples:
dateutil, git etc.
4. sys.platform
This helps you know about the platform. Everyone wants their program to run irrespective of the platform. And that’s where this command is mostly used.
Code:
sys.platform
Output:
If one needs to make code in aligned with the platform, here is what one can do.
Code:
if sys.platform.startswith('win'):
# win-specific code ...
elif sys.platform.startswith('aix'):
# AIX-specific code...
elif sys.platform.startswith('darwin'):
# MAC-specific code ..
elif sys.platform.startswith('linux'):
# Linux-specific code ..
5. sys.exit
In case of any exceptions in the program, there occurs the need of safe exit from the program. Sys.exit helps there.
Code:
def is_namevalid(name):
if any(i.isdigit() for i in name):
print("ERROR: Invalid feature set ")
sys.exit()
else:
print("Correct name")
Output:
6. sys.argv
This refers to a list in python, which contains arguments(command line) passed to the script. If someone types len(sys.argv), it will fetch you the count of the number of arguments. Someone working with command line arguments, will use sys.argv. Sys.argv[0] refers to the name of script.
Code:
import sys
print(sys.argv[0])
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
Say this python code is saved with name “sys.py” at certain location.
Now let’s go to command line, and type “python sys.py”.
Output:
However, if you type “python sys.py arg1”.
Output:
Thing to note here is that, first argument will always be script name, which in itself will be counted in counting the number of arguments.
7. sys.exitfunc
This is a parameter less function, which can be used by user to perform cleanup actions at program’s exit. This function no more exist in python 3.x. However, one can use “atexit” instead.
8. sys.stdin, sys.stdout, sys.stderr
These functions refers to file objects used by interpreter for the standard input, output and errors.
- Stdin is for interactive input like we use input(), raw_input(). Input is taken through stdin.
- Stdout is used for output like print(), output is printed actually through stdout.
- Stderr is to prompt the error message.
Code:
import sys
for j in (sys.stdin, sys.stdout, sys.stderr):
print (j)
Output:
As one can notice stdin, printed with mode ‘r’ which means reading while stdout and stderr are writing mode.
9. sys.setrecursionlimit(limit)
This function can help you limit the maximum depth of python interpreter. It helps you keep a stopover infinite recursion that can be a cause of overflow. However, highest possible limit depends on platform to platform. In case some keeps the limit higher, he/she should be aware of risk that can lead to crashes in python.
10.sys.getdefaultencoding()
It returns the default string encoding.
Let me show you in python environment.
Code:
print(sys.getdefaultencoding())
Output:
11. sys.setdefaultencoding()
This function helps you change the default encoding for strings in the python environment.
Example:
Code:
import sys
sys.setdefaultencoding('UTF8')
12. sys.exc_clear()
This function helps you to clear all information related to current or previous exceptions. This function is great to use, when you need to free the allocated resources and have to do object finalization.
Conclusion
All the above we saw, are important sets of functions available in the sys module. Sys module helps you to know about your working environment e.g. where your code is running, which platform it is running on, which python version and which interpreter is in use etc. One needs to go through these functions and start playing with it, in order to get a good grip over these functions.
Recommended Articles
This is a guide to Python Sys Module. Here we discuss the introduction to Python Sys Module along with the top 12 functions respectively. You may also have a look at the following articles to learn more –
40 Online Courses | 13 Hands-on Projects | 215+ Hours | Verifiable Certificate of Completion
4.8
View Course
Related Courses