The sys module provides access to Python interpreter internals. Here are the essentials.
Command Line Arguments
import sys
# Script name and arguments
print(sys.argv[0]) # Script name
print(sys.argv[1:]) # Arguments
# Example: python script.py arg1 arg2
# sys.argv = ["script.py", "arg1", "arg2"]For complex argument parsing, use argparse instead.
Exit Program
import sys
# Exit with status code
sys.exit(0) # Success
sys.exit(1) # Error
# Exit with message (goes to stderr)
sys.exit("Error: something went wrong")
# Same as
print("Error: something went wrong", file=sys.stderr)
sys.exit(1)Standard I/O
import sys
# Standard streams
sys.stdin # Input stream
sys.stdout # Output stream
sys.stderr # Error stream
# Read from stdin
line = sys.stdin.readline()
all_input = sys.stdin.read()
# Write to stdout
sys.stdout.write("Hello\n")
# Write to stderr
sys.stderr.write("Error!\n")
print("Error!", file=sys.stderr)
# Flush output
sys.stdout.flush()Redirect Output
import sys
from io import StringIO
# Capture output
old_stdout = sys.stdout
sys.stdout = StringIO()
print("This is captured")
output = sys.stdout.getvalue()
sys.stdout = old_stdout
# Or use contextlib
from contextlib import redirect_stdout
with redirect_stdout(StringIO()) as f:
print("Captured")
output = f.getvalue()Module Search Path
import sys
# List of paths Python searches for imports
print(sys.path)
# Add path at runtime
sys.path.insert(0, "/path/to/modules")
# Or append
sys.path.append("/another/path")Loaded Modules
import sys
# Dictionary of loaded modules
sys.modules
# Check if module is loaded
if "json" in sys.modules:
print("json is loaded")
# Get module object
json_module = sys.modules.get("json")
# Reload module (use importlib instead)
import importlib
importlib.reload(module)Python Version
import sys
# Version string
sys.version # "3.11.0 (default, ...)"
# Version tuple
sys.version_info
# sys.version_info(major=3, minor=11, micro=0, ...)
# Check version
if sys.version_info >= (3, 10):
print("Python 3.10+")
if sys.version_info < (3, 9):
sys.exit("Python 3.9+ required")Platform Information
import sys
sys.platform # "darwin", "linux", "win32"
sys.executable # Path to Python interpreter
sys.prefix # Installation prefix
# Platform-specific code
if sys.platform == "darwin":
print("macOS")
elif sys.platform == "linux":
print("Linux")
elif sys.platform == "win32":
print("Windows")Memory and Recursion
import sys
# Size of object in bytes
sys.getsizeof([1, 2, 3])
# Recursion limit
sys.getrecursionlimit() # Default: 1000
sys.setrecursionlimit(2000)
# Reference count
sys.getrefcount(object)Encoding
import sys
# Default encoding
sys.getdefaultencoding() # Usually "utf-8"
# Filesystem encoding
sys.getfilesystemencoding()
# Stdin/stdout encoding
sys.stdin.encoding
sys.stdout.encodingException Info
import sys
try:
raise ValueError("test")
except:
exc_type, exc_value, exc_tb = sys.exc_info()
print(f"Type: {exc_type}")
print(f"Value: {exc_value}")
print(f"Traceback: {exc_tb}")Common Patterns
Check Python version
import sys
MIN_VERSION = (3, 9)
if sys.version_info < MIN_VERSION:
sys.exit(f"Python {MIN_VERSION[0]}.{MIN_VERSION[1]}+ required")Read piped input
import sys
if not sys.stdin.isatty():
# Input is piped
data = sys.stdin.read()
else:
# Interactive mode
data = input("Enter data: ")Progress indicator
import sys
for i in range(100):
sys.stdout.write(f"\rProgress: {i+1}%")
sys.stdout.flush()
print() # Newline at endAdd project root to path
import sys
from pathlib import Path
# Add parent directory
sys.path.insert(0, str(Path(__file__).parent.parent))
# Now can import from project root
from mypackage import moduleDebug info
import sys
def debug_info():
print(f"Python: {sys.version}")
print(f"Platform: {sys.platform}")
print(f"Executable: {sys.executable}")
print(f"Encoding: {sys.getdefaultencoding()}")Quick Reference
import sys
# Arguments
sys.argv[0] # Script name
sys.argv[1:] # Arguments
# Exit
sys.exit(0) # Exit with code
sys.exit("Error") # Exit with message
# I/O
sys.stdin.read()
sys.stdout.write(s)
sys.stderr.write(s)
# Paths
sys.path # Module search paths
sys.executable # Python path
# Version
sys.version_info # Version tuple
sys.platform # OS platform
# Memory
sys.getsizeof(obj) # Object size
sys.getrecursionlimit()The sys module is your window into the Python runtime. Use it for system interaction and runtime configuration.
React to this post: