×

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

Python Dictionary setdefault() method

Python Dictionary setdefault() method The dictionary.setdefault () method in Python returns the value of the item with the specified key. Syntax dictionary.setdefault(keyname, value) Parameter keyname- This parameter represents the keyname of the item you want...

1 minute read.

Find whether the given stringnumber is palindrome or not

Problem statement Sam is found of playing with strings. One day he thought of finding whether a string is a palindrome or not. He wanted to develop a computer process to...

2 minutes read.

Python oct() function

Python oct() function The oct() function in Python converts an integer number to an octal string prefixed with “0o”. Syntax oct(x) Parameter x: This parameter represents an Integer Number Return This function returns an octal string. Example 1 #...

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

Python Dictionary

Dictionary in Python is an unordered collection of data values, which is used to store data values like a map. Unlike different data types that hold just individual assets as...

4 minutes read.

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

4 minutes read.

Cursor in Python

The cursor is an item that aids in query execution and records retrieval from databases. The cursor is crucial to the execution of the query. In-depth information on the execution...

7 minutes read.

Difference between python list and tuple

In this tutorial, we will understand the key differences between python lists and tuples in python. Firstly, let us see the similarities between Lists and Tuples. Both are two data types...

4 minutes read.

How to check the version of the Python Interpreter?

As we all know what an interpreter is, and how important it is. We should also be aware of the fact that it is important to have knowledge of the...

2 minutes read.

Flutter with tensor flow in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The...

3 minutes read.

Python max() function

Python max() function The max() function in Python returns the largest item in an iterable or the largest of two or more arguments. Syntax max(iterable, *[, key, default])               or max(arg1, arg2, *args[, key])   Parameter arg1, arg2, *args: This...

1 minute read.

Difference Between Python and Scala

What is Python? Python is a high-level general-purpose interpreted programing language. It is used for multi general-purpose work such as language construct as well as its object-oriented approach aims to help...

4 minutes read.

Scrimba python

Scrimba allows you to study whenever and wherever the topics or concepts you want. It also replaces classroom instruction with interactive screencasts, live events, and student-to-student help. Scrimba is an interactive...

3 minutes read.

Python Tkinter Tutorial

What is Tkinter? Tkinter is GUI library of Python. When we integrated Tinkter with Python, it provides an easy and quick way to develop GUI applications. It provides the Tk GUI...

14 minutes read.

How to Install PIP In Python

How to Install PIP In Python The libraries for Python have made our work easier than we expected. From a simple addition of two numbers to applying algorithms on the big...

4 minutes read.

Palindrome In Python

What is Palindrome? A Palindrome can be defined as the number or a string that resides unchanged when it is reversed. Example: 14341 Output: Yes, this is a Palindrome number Example: RACECAR Output: Yes, this...

2 minutes read.

Python String istittle() method

Python String istittle() method The string.istittle() method returns a boolean value true if the string is a titlecased string and there is at least one character, for example uppercase characters may...

2 minutes read.

How to run a Python file in CMD

Introduction Today, let us learn about how to run a Python file using cmd. Cmd is nothing but command prompt. So first let us know how to run a Python code...

4 minutes read.

_name_ in Python

Introduction: The code at level 0 indentation is to be performed when the command to run a Python program is supplied to the interpreter because Python does not have a main() function...

4 minutes read.

Assertion error in python

In this article, we will discuss assertions in the python programming language. Assertion: Assertions are a way of telling a program to test a certain condition and trigger an error if the...

3 minutes read.