×

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

Best Database for Python

Database The collection of structured data or information in an organized format in a computer system is known as Database. The data is inserted, deleted, updated, controlled, or manipulated in a...

6 minutes read.

Isreal() Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

4 minutes read.

Python System Command

To execute a program in Python, we need to execute some shell commands to run our program on the computer. Python will provide some shell commands in our background to...

3 minutes read.

Python Dictionary keys() method

Python Dictionary keys() method The dictionary.keys() method in Python returns a view object that displays a list of all the keys in the dictionary Syntax dictionary.keys() Parameter NA Return This method returns a view object that displays...

2 minutes read.

Insertion Sort using Python

Insertion sort is a type of sorting technique that is used for sorting an array with random elements. Using sorting methods, any unsorted array can be sorted into ascending or...

3 minutes read.

Python Set symmetric_difference() method

Python Set symmetric_difference() method The set.symmetric_difference() method returns a new set, which is the symmetric difference of two sets. The returned set contains only the unique items and, hence, deleting the common elements of...

2 minutes read.

Get Bounding Box Co-ordinates Python

Python: 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 faster way....

6 minutes read.

Difference between Input() and raw_input() functions in Python

There are two input functions in Python that are used for taking input are given below: raw_input()input() What is raw_input() Function? raw_input() function is a built-in function in Python. It is used to...

6 minutes read.

What is the re.sub() function in Python

There. sub () function is used to return a string by replacing the occurrences of a specific character or pattern with a replacement string. To use this function, import the...

3 minutes read.

Collections in python

In this tutorial, we will see what is collection in python.  Further, we will see in-depth the different kinds of collections in python. Collections Collections in python are the built-in module used...

9 minutes read.

Make Notepad using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

5 minutes read.

Python Modules List

Python is like an ocean. If you have been working with Python, you might’ve already heard the word module. When we solve a problem in mathematics, there will be several...

3 minutes read.

Python Arithmetic Operators

An arithmetic operator is a mathematical operator that is used to operate on two operands. Based on the operator used, action is performed on the operands, and output is delivered. Following...

3 minutes read.

How to read data from com port in python

Comport, the I/O interface is known as a COM port that allows the connection for a serial device to a computer. COM ports are sometimes referred to as serial ports....

3 minutes read.

Merge Sort using Python

Merge Sort is a technique that is used for sorting elements in an array using a special method known as divide and conquer. It is the best example of the...

5 minutes read.

Python Set symmetric_difference_update() method

Python Set symmetric_difference_update() method The set.symmetric_difference_update() method in Python updates the original set by removing items that are present in both sets and inserting the other items of the set. Syntax set.symmetric_difference_update(set1) Parameter set- This parameter represents the first...

2 minutes read.

Convert String to Binary in Python

String to binary The strings can be defined as the array of Unicode code characters. Binary Binary is defined as the number system which consists two symbols 0 and 101. It is base-2...

2 minutes read.

Python 2.7 data structures

The rundown information type has a few additional techniques. Here is every one of the strategies for listing objects: list.append(x): Add a thing to the furthest limit of the rundown; comparable...

9 minutes read.

Python String isdigit() method

Python String isdigit() method The string.isdigit() method returns a boolean value true if all characters in the string are digits else for any other value it returns false. Syntax string.isdigit() Parameter NA Return This method returns a...

2 minutes read.

Python hash() function

Python hash() function The hash() function in Python returns the hash value of the object (if it has one).  Syntax hash(object) Parameter obj : This parameter represents the object which we need to convert into hash. Return This...

1 minute read.