Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
OS Module in Python with Examples
Next article icon

Python sys Module

Last Updated : 18 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

The sys module in Python provides various functions and variables that are used to manipulate different parts of the Python runtime environment. It allows operating on the interpreter as it provides access to the variables and functions that interact strongly with the interpreter. Let’s consider the below example.

Sys Module in Python

Python sys.version

In this example, sys.version is used which returns a string containing the version of Python Interpreter with some additional information. This shows how the sys module interacts with the interpreter. Let us dive into the article to get more information about the sys module.

Python3

import sys
print(sys.version)
                      
                       

Output:

3.6.9 (default, Oct  8 2020, 12:12:24)  [GCC 8.4.0] 

Input and Output using Python Sys

The sys modules provide variables for better control over input or output. We can even redirect the input and output to other devices. This can be done using three variables – 

  • stdin
  • stdout
  • stderr

Read from stdin in Python

stdin: It can be used to get input from the command line directly. It is used for standard input. It internally calls the input() method. It, also, automatically adds ‘\n’ after each sentence.

Example:

This code reads lines from the standard input until the user enters ‘q’. For each line, it prints “Input : ” followed by the line. Finally, it prints “Exit”.

Python3

import sys
for line in sys.stdin:
    if 'q' == line.rstrip():
        break
    print(f'Input : {line}')
 
print("Exit")
                      
                       

Output:

Python sys.stdout Method

stdout: A built-in file object that is analogous to the interpreter’s standard output stream in Python. stdout is used to display output directly to the screen console. Output can be of any form, it can be output from a print statement, an expression statement, and even a prompt direct for input. By default, streams are in text mode. In fact, wherever a print function is called within the code, it is first written to sys.stdout and then finally on to the screen. 

Example:

This code will print the string “Geeks” to the standard output. The sys.stdout object represents the standard output stream, and the write() method writes the specified string to the stream.

Python3

import sys
sys.stdout.write('Geeks')
                      
                       

Output
Geeks  

stderr function in Python

stderr: Whenever an exception occurs in Python it is written to sys.stderr. 

Example:

This code will print the string “Hello World” to the standard error stream. The sys.stderr object represents the standard error stream, and the print() function writes the specified strings to the stream.

Python3

import sys
def print_to_stderr(*a):
    print(*a, file = sys.stderr)
 
print_to_stderr("Hello World")
                      
                       

Output:

python-stderr

Command Line Arguments

Command-line arguments are those which are passed during the calling of the program along with the calling statement. To achieve this using the sys module, the sys module provides a variable called sys.argv. It’s main purpose are:

  • It is a list of command-line arguments.
  • len(sys.argv) provides the number of command-line arguments.
  • sys.argv[0] is the name of the current Python script.

Example: Consider a program for adding numbers and the numbers are passed along with the calling statement.

This code calculates the sum of the command-line arguments passed to the Python script. It imports the sys module to access the command-line arguments and then iterates over the arguments, converting each one to an integer and adding it to a running total. Finally, it prints the total sum of the arguments.

Python3

import sys
n = len(sys.argv)
print("Total arguments passed:", n)
print("\nName of Python script:", sys.argv[0])
print("\nArguments passed:", end = " ")
for i in range(1, n):
    print(sys.argv[i], end = " ")
Sum = 0
for i in range(1, n):
    Sum += int(sys.argv[i])
     
print("\n\nResult:", Sum)
                      
                       

Output:

python-command-line-arguments

Exiting the Program

sys.exit([arg]) can be used to exit the program. The optional argument arg can be an integer giving the exit or another type of object. If it is an integer, zero is considered “successful termination”.

Note: A string can also be passed to the sys.exit() method.

Example: 

This code checks if the age is less than 18. If it is, it exits the program with a message “Age less than 18”. Otherwise, it prints the message “Age is not less than 18”. The sys.exit() function takes an optional message as an argument, which is displayed when the program exits.

Python3

import sys
age = 17
if age < 18:
    sys.exit("Age less than 18")    
else:
    print("Age is not less than 18")
                      
                       

Output:

An exception has occurred, use %tb to see the full traceback.  SystemExit: Age less than 18  

Working with Modules

sys.path is a built-in variable within the sys module that returns the list of directories that the interpreter will search for the required module. 

When a module is imported within a Python file, the interpreter first searches for the specified module among its built-in modules. If not found it looks through the list of directories defined by sys.path.

Note: sys.path is an ordinary list and can be manipulated.

Example 1: Listing out all the paths

This code will print the system paths that Python uses to search for modules. The sys.path list contains the directories that Python will search for modules when it imports them.

Python3

import sys
print(sys.path)
                      
                       

Output:

Example 2: Truncating the value of sys.path

This code will print an error message because the pandas module is not in the sys.path list. The sys.path list is a list of directories that Python will search for modules when it imports them. By setting the sys.path list to an empty list, the code effectively disables Python’s ability to find any modules.

Python3

import sys
sys.path = []
import pandas
                      
                       

Output:

ModuleNotFoundError: No module named 'pandas'  

sys.modules return the name of the Python modules that the current shell has imported.

Example:

This code will print a dictionary of all the modules that have been imported by the current Python interpreter. The dictionary keys are the module names, and the dictionary values are the module objects.

Python3

import sys
print(sys.modules)
                      
                       

Output:

Reference Count

sys.getrefcount() method is used to get the reference count for any given object. This value is used by Python as when this value becomes 0, the memory for that particular value is deleted.

Example:

This code prints the reference count of the object a. The reference count of an object is the number of times it is referenced by other objects. An object is garbage collected when its reference count reaches 0, meaning that it is no longer referenced by any other objects

Python3

import sys
a = 'Geeks'
print(sys.getrefcount(a))
                      
                       



Output
4  

More Functions in Python sys

FunctionDescription
sys.setrecursionlimit()sys.setrecursionlimit() method is used to set the maximum depth of the Python interpreter stack to the required limit.
sys.getrecursionlimit() methodsys.getrecursionlimit() method is used to find the current recursion limit of the interpreter or to find the maximum depth of the Python interpreter stack.
sys.settrace()It is used for implementing debuggers, profilers and coverage tools. This is thread-specific and must register the trace using threading.settrace(). On a higher level, sys.settrace() registers the traceback to the Python interpreter
sys.setswitchinterval() methodsys.setswitchinterval() method is used to set the interpreter’s thread switch interval (in seconds).
sys.maxsize()It fetches the largest value a variable of data type Py_ssize_t can store.
sys.maxintmaxint/INT_MAX denotes the highest value that can be represented by an integer.
sys.getdefaultencoding() methodsys.getdefaultencoding() method is used to get the current default string encoding used by the Unicode implementation.


 



Next Article
OS Module in Python with Examples
author
abhishek1
Improve
Article Tags :
  • Python
  • Python-sys
Practice Tags :
  • python

Similar Reads

  • Python Modules
    Python Module is a file that contains built-in functions, classes,its and variables. There are many Python modules, each with its specific work. In this article, we will cover all about Python modules, such as How to create our own simple module, Import Python modules, From statements in Python, we
    7 min read
  • Python Arrays
    Lists in Python are the most flexible and commonly used data structure for sequential storage. They are similar to arrays in other languages but with several key differences: Dynamic Typing: Python lists can hold elements of different types in the same list. We can have an integer, a string and even
    10 min read
  • asyncio in Python
    Asyncio is a Python library that is used for concurrent programming, including the use of async iterator in Python. It is not multi-threading or multi-processing. Asyncio is used as a foundation for multiple Python asynchronous frameworks that provide high-performance network and web servers, databa
    4 min read
  • Calendar in Python
    Python has a built-in Python Calendar module to work with date-related tasks. Using the module, we can display a particular month as well as the whole calendar of a year. In this article, we will see how to print a calendar month and year using Python. Calendar in Python ExampleInput: yy = 2023 mm =
    2 min read
  • Python Collections Module
    The collection Module in Python provides different types of containers. A Container is an object that is used to store different objects and provide a way to access the contained objects and iterate over them. Some of the built-in containers are Tuple, List, Dictionary, etc. In this article, we will
    13 min read
  • Working with csv files in Python
    Python is one of the important fields for data scientists and many programmers to handle a variety of data. CSV (Comma-Separated Values) is one of the prevalent and accessible file formats for storing and exchanging tabular data. In article explains What is CSV. Working with CSV files in Python, Rea
    10 min read
  • Python datetime module
    In Python, date and time are not data types of their own, but a module named DateTime in Python can be imported to work with the date as well as time. Python Datetime module comes built into Python, so there is no need to install it externally. In this article, we will explore How DateTime in Python
    14 min read
  • Functools module in Python
    Functools module is for higher-order functions that work on other functions. It provides functions for working with other functions and callable objects to use or extend them without completely rewriting them. This module has two classes - partial and partialmethod. Partial class A partial function
    6 min read
  • hashlib module in Python
    A Cryptographic hash function is a function that takes in input data and produces a statistically unique output, which is unique to that particular set of data. The hash is a fixed-length byte stream used to ensure the integrity of the data. In this article, you will learn to use the hashlib module
    5 min read
  • Heap queue or heapq in Python
    A heap queue or priority queue is a data structure that allows us to quickly access the smallest (min-heap) or largest (max-heap) element. A heap is typically implemented as a binary tree, where each parent node's value is smaller (for a min-heap) or larger (for a max-heap) than its children. Howeve
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences