2 min read

Python Sys Module

The sys module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It is always available.

Importing the Module

import sys

Command Line Arguments

The list of command line arguments passed to a Python script. sys.argv[0] is the script name.

import sys

print(f"Script name: {sys.argv[0]}")
print(f"Arguments: {sys.argv[1:]}")

Exiting the Program

sys.exit() allows you to exit from Python. You can pass an optional integer exit code (0 is success, non-zero is error) or a string (printed to stderr and code 1 returned).

import sys

# Exit with success
# sys.exit(0)

# Exit with error message
# sys.exit("An error occurred")

Standard I/O

File objects corresponding to the interpreter’s standard input, output, and error streams.

import sys

# Write to stdout
sys.stdout.write("Hello stdout\n")

# Write to stderr
sys.stderr.write("Hello stderr\n")

# Read from stdin
# input_data = sys.stdin.readline()

Python Path

sys.path is a list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default.

import sys

print(sys.path)

# Add a directory to the path
sys.path.append('/path/to/my/modules')

System Information

Platform

print(sys.platform) # e.g., 'linux', 'win32', 'darwin'

Python Version

print(sys.version)
print(sys.version_info)

Modules

sys.modules is a dictionary that maps module names to modules which have already been loaded.

import sys

print(sys.modules.keys())

Reference Counting

sys.getrefcount() returns the reference count of an object.

import sys

a = []
print(sys.getrefcount(a))

programming/python/python