×

Sys Module in Python

What are Modules?

The Modules are the kind of files that contain Python statements and definitions. The module is known by the name of the file followed by the suffix “.py”. It can define variables, functions, and classes. It helps in making code easy to use and easier to understand by grouping all code related to each other into a common module. Thus, the code appears organized logically.

Advantages of using Modules

  • These can be easily renamed and used freely anywhere in our code.
  • It reduces code redundancy.
  • A code fragment can be used multiple times without writing it again and again.
  • The modules can be built-in or the user can also create them. For example, math, Tkinter, random, etc. are built-in modules; and you can create different modules according to your comfort.

What is sys Module?

Whenever we want to make changes in the different parts of the Python run time environment, we require some different functions and variables, The Sys module provides the same and makes our task easy. This module helps us to operate on the interpreter, as it provides different functions and variables that help in interacting with the interpreter.

Example:

importsys
  
a = sys.version
print( a )

Output:

3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 19:00:18) [MSC v.1929 64 bit (AMD64)]

As we can see in the output of the above-given example, the sys.version returns the version of the Python interpreter along with some additional information, and this all information is returned in form of a string. This shows the way the sys module interconnect with the interpreter and returns the version of Python.

Input and Output using sys module

Using the sys module, we can use the input and output on our own terms due to the variables provided by this module. The following three variables can be used to do so:

  1. stdin
  2. stdout
  3. stderr

stdin

This variable is used to take input directly from the command line. It stands for “standard input”, this variable calls the input() method. This variable automatically adds the “\n” after every sentence.

Example:

importsys 
  
  
forxinsys.stdin: 
    if'q'==x.rstrip(): 
        break
    print(f'Input : {line}') 
  
print("Exit") 

Output:

Sys Module in Python

stdout

It is a built-in file object which is almost similar to the output stream in Python. It is used to return output directly to the screen console. The returned output may have any form, it can be output from an expression statement, a print statement, or a prompt direct for input. The streams are in text mode by default. When we want to print something, we simply use the print function, but internally, first, the required expression is written to sys.stdout and then displayed on the output screen.

Example:

importsys
  
  
sys.stdout.write('How are you?')

Output:

How are you?

stderr

In Python, all the encountered exceptions are written sys.stderr.

Example:

importsys 
  
  
defprtStderr(*x ): 
  
    # In this function, x is an array that stores the object 
    # that is passed as the argument to the function
    print(*x, file=sys.stderr) 
  
prtStderr("Hey!! How are you?") 

Output:

Hey!! How are you?

Command Line Arguments

Arguments passed during calling a program along with the calling statement is called command line argument. The sys module can be used to achieve this too, as this module has a variable known as sys.argv which helps in doing so. The main aim of this variable is:

  • It returns the list of command line arguments.
  • len(sys.argv) is used to get the number of command line arguments.
  • The name of the current Python script is given by: sys.argv[0].

Example:

# A code in Python to illustrate
# command line arguments
  
importsys
  
# Total number arguments
l=len(sys.argv)
print("Total number of arguments passed:", l)
  
print("\nName of Python script:", sys.argv[0])
 
# Name of thearguments passed 
print("\nArguments passed:", end =" ")
forjinrange(1, l):
    print(sys.argv[ j ], end =" ")
      
# Sum of numbers passed as arguments
sum=0
forkinrange(1, l):
    sum+=int(sys.argv[ k ])
      
print("\n Final result:", sum)

Output:

Sys Module in Python

Exiting the program

To exit any program, we use sys.exit([arg]). In this statement, the argument “arg” can be taken as an integer giving the exit or any other type of object. A zero is considered as a successful termination if the argument passed is an integer.

Note: You can also pass a string as an argument in this statement.

Example:

# A code in Python to illustrate 
# the sys.exit() statement
  
  
importsys 
  
  
age =15
  
  
ifage <18: 
      
    # Exits the program 
    sys.exit("Age entered is less than 18")     
else: 
    print("Age entered is not less than 18") 

Output:

Age entered is not less than 18

Working with modules

To return the list of directories that will be searched by the interpreter for the required module can be accessed with the help of sys.path which is a built-in variable in the sys module.

When we import any module in a Python file, first, the specified module is searched within the built-in modules by the interpreter, if found good. If not then it searches among the list of directories provided by sys.path.

Note: sys.path is an ordinary list, and it can be manipulated according to the requirement of the user.

Example 1: Printing all paths

importsys 
x = sys.path
print(x)

Output:

Sys Module in Python

Example 2: Removing all the values present in sys.path

importsys
  
# Removing the values
sys.path =[]
  
# Importing numpy after removing all
# the values from sys.path
importnumpy

Output:

Sys Module in Python

sys.module

This statement is used to display the names of the modules imported by the current Python shell.

Example:

importsys
  
x = sys.modules
print(x)

Output:

Sys Module in Python

Reference Count

To know about the reference count of any object, we use the sys.getrefcount() method. Python use this value to perform operations, and when this value becomes 0, the memory for that particular object is freed (deleted).

Example:

importsys
  
a ='How are you'
b =sys.getrefcount(a)
  
print( b )

Output:

3

Some more functions in the Python sys module

  • sys.setrecursionlimit() method: This method is used to set the limit of the maximum depth of the stack of the Python interpreter.
  • sys.getrecursionlimit() method: This method is used to find the maximum depth of the Python interpreter stack, and it can also be used to get the current recursion limit of the interpreter.
  • sys.settrace () method: This method is used to implement profilers, coverage tools, and debuggers.
  • sys.switchinterval () method: This method is used to set the thread switch interval (in seconds).
  • sys.maxsize () method: This method is used to get the largest value that a variable can store of data type Py_ssize_t.
  • sys.maxint () method: This method is used to denote the highest value that the integer is capable to represent.
  • sys.getdefaultencoding () method: This method is used to fetch the default string encoding that is currently being used by the Unicode Implementation.

Related Topics

Nested List in Python

The list is an inbuilt sequential data type in Python. It is a very useful and frequently used data type. A list can store any number of data items of...

4 minutes read.

Python Escape Characters

In this tutorial, we will learn how to use the Escape Characters in Python. Escape Character: Escape Characters are used for some special meaning in our statements. It is denoted or represented...

3 minutes read.

Python Dictionary popitem() method

Python Dictionary popitem() method The dictionary.popitem() method in Python removes the item that was last inserted into the dictionary. Syntax dictionary.popitem() Parameter NA Return This method returns an arbitrary element (key, value) pair from the given dictionary...

1 minute read.

Global variables in python

In Python, considering the scope, variables are categorized into global and local variables. In this article, we will discuss these two types along with examples. Any variable holds a value in...

4 minutes read.

Python PPTX

Python-pptx is a python library that enables the user to create and update PowerPoint (.pptx) presentations. It is used to create modified PowerPoint presentations from the db content that can...

10 minutes read.

Python Empty Tuple

How to Create an Empty Tuple Tuple A tuple is a data structure used to store non-homogeneous data elements. These non-homogeneous data elements consist of integer data type, character data type, String...

3 minutes read.

Python object()

Python object() class The object class in Python is a base for all classes. It returns a new featureless object. Syntax class object Parameter NA Return It returns a new featureless object. Example 1 # Python program explaining # the object()...

1 minute read.

Working with CSV files in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

7 minutes read.

Python Fit Transform

In machine learning, fit (), transform(), fit transform () methods are provided by scikit learn package. This package is used in model fitting and data processing. These methods are implemented...

2 minutes read.

os.rename() method in Python

In Python, the os module provides the capacity to interact with the operating system. The operating system comes under the Python module. In this module, Python provides a specific feature...

3 minutes read.

Difference between Python and CPP

Difference between Python and C++ We all know that both C++ and Python are two of the most popular programming languages. Both C++ and Python shares some basic similarities such as...

6 minutes read.

Number pattern in Python

Number pattern in Python: This article explains how to print number patterns in Python. The FOR loop, while loop, and range() functions are used in the following Python programs to...

4 minutes read.

Idle python download for Windows

Here, we will be discussing how to get the answer to all questions related to installing Python on Windows. What is IDLE? Integrated Development and Learning Environment, or IDLE, is a shorthand....

3 minutes read.

Check Letter in a String Python

Checking a specific letter or a character in a given string or a string which is taken as an input from the user is possible in Python in broadly three...

3 minutes read.

Yield vs Return in Python

In this article, you will learn about " Yield " and " Return " in Python. You will also understand the difference between " Yield " and " Return "...

6 minutes read.

Iterate a Dictionary in Python – Part 2

In this tutorial, we will learn above various methods used to Iterate a Dictionary in Python. Dictionary: In Python, a dictionary is an unordered collection of data values that is used to...

3 minutes read.

Python: SetBitmap() function in wxPython

SetBitmap() function In the last tutorial, we have discussed about the GetLabelText() function of wx.MenuItem class which is one of the important function of this class. Now, in this tutorial, we...

6 minutes read.

Python random.seed() function

The random module in Python produces a random number or pseudo-random data, that is, deterministic. The seed function records the state of a random function to provide the same random...

6 minutes read.

Curdir Python

Python Programming Language Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

3 minutes read.

Parameter Passing in Python

In Python, when we characterize capabilities with default values for specific boundaries, it is said to have its contentions set as a possibility for the client. Clients can either pass their...

3 minutes read.