Python sys Module – Important Functions

Free Python course with 25 real-time projects Start Now!!

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.

Python sys Module - Important Functions

Python sys Module – Important Functions

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

‘3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)]’
>>> sys.version_info

Output

sys.version_info(major=3, minor=7, micro=0, releaselevel=’final’, serial=0)
>>> sys.getrecursionlimit() #Get maximal recursion depth

Output

1000
>>> sys.setrecursionlimit(1500) #Set maximal recursion depth
>>> sys.getrecursionlimit()

Output

1500

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

C:\Users\Ayushi\Desktop>py sysdemo.py 2 3
[‘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

42
>>> print(x)

Output

42
>>> def show(x):
       print("Output:",x)
>>> sys.displayhook=show
>>> x

Output

42
>>> print(x)

Output

None

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

Type in value:  23

The following piece of code lets us print to the screen:

>>> sys.stdout.write('Way to write')

Output

Way to write12
>>> sys.stdout.write('Way to write\n')

Output

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.

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
Python sys Module

sys Module in Python

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

[”, ‘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.

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
Python sys Module

Exiting Current Flow of Execution

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

37

To get the name of the platform we’re running Python on, we make a call to sys.platform in Python:

>>> sys.platform

Output

‘win32’

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

Hello
>>> saveout=sys.stdout
>>> fsock=open('out.log','w')
>>> sys.stdout=fsock
>>> print('Message to log')
>>> sys.stdout=saveout
>>> fsock.close()
Python sys Module

Redirecting Output in Python

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()
Python sys Module

Redirecting Error Information in Python sys Module

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
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.

Python sys Module

Python sys Module – Functions

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

  1. What is sys module in Python?
  2. What is the most common use of Python sys library?
  3. What is Python sys argv?
  4. What is OS and SYS in Python?
  5. 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 | Facebook

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.