sys
The sys module gives you access to variables and functions that interact with the Python interpreter and the underlying system. It is one of the most commonly used standard library modules, particularly for tasks like reading command-line arguments, exiting programs, and inspecting the runtime environment.
Command-Line Arguments
sys.argv
sys.argv is a list containing the command-line arguments passed to the Python script. The first element (sys.argv[0]) is the script name itself.
# script.py
import sys
print(f"Script name: {sys.argv[0]}")
print(f"Arguments: {sys.argv[1:]}")
# Running: python script.py foo bar
# Output:
# Script name: script.py
# Arguments: ['foo', 'bar']
sys.exit()
sys.exit() terminates the program. You can pass an exit code (0 for success, non-zero for error) or a string message.
import sys
def validate_input(value):
if not value.isdigit():
sys.exit("Error: Please enter a valid number")
return int(value)
# sys.exit(0) exits successfully
# sys.exit(1) exits with an error code
# sys.exit("message") prints the message and exits with code 1
Python Interpreter Information
sys.version and sys.version_info
These provide details about the Python interpreter:
import sys
print(sys.version)
# 3.12.0 (main, Oct 2 2023, 13:15:55) [GCC 9.4.0]
print(sys.version_info)
# sys.version_info(major=3, minor=12, micro=0, releaselevel='final', serial=0)
# Useful for version-specific code
if sys.version_info >= (3, 11):
print("Using Python 3.11+ features")
sys.executable
Returns the absolute path of the Python interpreter executable:
import sys
print(sys.executable)
# /usr/bin/python3
sys.platform
Identifies the operating system:
import sys
print(sys.platform)
# linux (on Linux), win32 (on Windows), darwin (on macOS)
# Practical use
if sys.platform == "win32":
path_sep = "\\"
elif sys.platform == "darwin" or sys.platform == "linux":
path_sep = "/"
Input/Output Streams
sys.stdin, sys.stdout, sys.stderr
These provide access to the standard input, output, and error streams:
import sys
# Reading from stdin
user_input = sys.stdin.readline()
print(f"You entered: {user_input}")
# Writing to stderr
import sys
sys.stderr.write("This is an error message\n")
# Redirecting stdout
import sys
old_stdout = sys.stdout
sys.stdout = open("output.txt", "w")
print("This goes to the file")
sys.stdout = old_stdout
Module and Import Information
sys.modules
A dictionary mapping module names to loaded modules. Useful for debugging or dynamic imports:
import sys
# Check if a module is loaded
if "requests" in sys.modules:
print("requests is already loaded")
# See all loaded modules
print(list(sys.modules.keys())[:10])
# ['sys', 'builtins', '_frozen_importlib', ...]
sys.path
A list of directories where Python searches for modules:
import sys
# Add a custom path
sys.path.append("/path/to/my/modules")
# See search paths
print(sys.path)
Runtime Limits
sys.getrecursionlimit() and sys.setrecursionlimit()
Control the maximum depth of the Python call stack:
import sys
print(sys.getrecursionlimit())
# 1000 (default)
# Increase the limit for deep recursion
sys.setrecursionlimit(2000)
# Be careful—too high can cause a crash
Object Sizes
sys.getsizeof()
Returns the size of an object in bytes:
import sys
print(sys.getsizeof(42))
# 28
print(sys.getsizeof("hello"))
# 53
print(sys.getsizeof([1, 2, 3]))
# 88
Note: This includes the object’s overhead and refers to GC-tracked memory, not the actual memory footprint.
Common Patterns
Detecting interactive mode
import sys
if sys.flags.interactive:
print("Running in interactive mode")
else:
print(f"Running script: {sys.argv[0]}")
Getting the call stack
import sys
def deep_function():
frame = sys._getframe()
current = frame.f_back
while current is not None:
print(f"Function: {current.f_code.co_name}")
current = current.f_back
def middle():
deep_function()
def top():
middle()
top()
Working with the AST
import sys
import ast
code = "print('hello')"
tree = ast.parse(code)
print(ast.dump(tree))