The sys module is your gateway to Python's internals and the system it runs on. Here are the essential features you'll use regularly.
Command Line Arguments
import sys
# sys.argv is the argument list
# sys.argv[0] is the script name
print(f"Script: {sys.argv[0]}")
print(f"Arguments: {sys.argv[1:]}")
# Example: python script.py arg1 arg2
# sys.argv = ['script.py', 'arg1', 'arg2']Standard Streams
import sys
# Standard streams
sys.stdout.write("This goes to stdout\n")
sys.stderr.write("This goes to stderr\n")
# Read from stdin
line = sys.stdin.readline()
# Redirect output
original_stdout = sys.stdout
sys.stdout = open('output.txt', 'w')
print("This goes to file")
sys.stdout = original_stdoutExiting the Program
import sys
# Exit with status code
sys.exit(0) # Success
sys.exit(1) # Error
sys.exit("Error message") # Prints to stderr, exits with 1
# Check if running interactively
if hasattr(sys, 'ps1'):
print("Interactive mode")Python Version Info
import sys
# Version string
print(sys.version)
# '3.11.0 (main, Oct 24 2022, 00:00:00) [GCC 11.2.0]'
# Version tuple
print(sys.version_info)
# sys.version_info(major=3, minor=11, micro=0, ...)
# Check version
if sys.version_info >= (3, 10):
print("Python 3.10+")
# Implementation
print(sys.implementation.name) # 'cpython'Platform Information
import sys
# Platform identifier
print(sys.platform) # 'linux', 'darwin', 'win32'
# Byte order
print(sys.byteorder) # 'little' or 'big'
# Max values
print(sys.maxsize) # Maximum list/string size
print(sys.maxunicode) # Maximum Unicode code point
# Executable path
print(sys.executable) # '/usr/bin/python3'Module Search Path
import sys
# Where Python looks for modules
print(sys.path)
# Add to path at runtime
sys.path.insert(0, '/my/custom/path')
# Or append
sys.path.append('/another/path')
# Remove from path
sys.path.remove('/unwanted/path')Loaded Modules
import sys
import json
# All loaded modules
print(list(sys.modules.keys())[:10])
# Check if module is loaded
if 'json' in sys.modules:
print("json is loaded")
# Get module object
json_module = sys.modules['json']
# Reload a module (remove from cache)
if 'mymodule' in sys.modules:
del sys.modules['mymodule']Memory and Object Info
import sys
# Size of object in bytes
print(sys.getsizeof([1, 2, 3])) # ~88 bytes
print(sys.getsizeof("hello")) # ~54 bytes
print(sys.getsizeof({"a": 1})) # ~64 bytes
# Reference count
x = [1, 2, 3]
print(sys.getrefcount(x)) # Usually 2+ (includes temporary)
# Recursion limit
print(sys.getrecursionlimit()) # Default: 1000
sys.setrecursionlimit(2000) # Increase if neededException Info
import sys
try:
1 / 0
except:
# Get exception info
exc_type, exc_value, exc_tb = sys.exc_info()
print(f"Type: {exc_type}")
print(f"Value: {exc_value}")
print(f"Traceback: {exc_tb}")Profiling and Tracing
import sys
def trace_calls(frame, event, arg):
if event == 'call':
print(f"Calling: {frame.f_code.co_name}")
return trace_calls
# Enable tracing
sys.settrace(trace_calls)
# Your code here
def example():
pass
example()
# Disable tracing
sys.settrace(None)
# Profiling hook
sys.setprofile(profile_callback)Hooks
import sys
# Display hook (modifies REPL output)
def custom_display(value):
if value is not None:
print(f"Result: {value!r}")
sys.displayhook = custom_display
# Exception hook (unhandled exceptions)
def custom_excepthook(exc_type, exc_value, exc_tb):
print(f"Unhandled exception: {exc_value}")
sys.excepthook = custom_excepthookFlags and Configuration
import sys
# Command line flags
print(sys.flags)
# sys.flags(debug=0, inspect=0, interactive=0, optimize=0, ...)
# Check if optimized
if sys.flags.optimize:
print("Running with -O")
# Float info
print(sys.float_info.max) # Maximum float value
print(sys.float_info.epsilon) # Smallest difference
# Int info
print(sys.int_info.bits_per_digit) # Bits in digitInterning Strings
import sys
# Intern a string for faster comparison
a = sys.intern("hello")
b = sys.intern("hello")
print(a is b) # True (same object)
# Useful for repeated string comparisons
keys = [sys.intern(k) for k in ["key1", "key2", "key3"]]Call Stack
import sys
def get_caller_name():
"""Get name of calling function."""
frame = sys._getframe(1)
return frame.f_code.co_name
def example():
print(f"Called by: {get_caller_name()}")
def main():
example()
main() # "Called by: main"stdin/stdout Encoding
import sys
# Default encoding
print(sys.getdefaultencoding()) # 'utf-8'
# stdin/stdout encoding
print(sys.stdin.encoding) # 'utf-8'
print(sys.stdout.encoding) # 'utf-8'
# File system encoding
print(sys.getfilesystemencoding()) # 'utf-8'Common Patterns
import sys
# Script guard
if __name__ == '__main__':
if len(sys.argv) < 2:
print(f"Usage: {sys.argv[0]} <arg>", file=sys.stderr)
sys.exit(1)
main(sys.argv[1])
# Platform-specific code
if sys.platform == 'win32':
path_sep = '\\'
else:
path_sep = '/'
# Python version check
if sys.version_info < (3, 8):
print("Python 3.8+ required")
sys.exit(1)Quick Reference
| Attribute/Function | Purpose |
|---|---|
sys.argv | Command line arguments |
sys.exit() | Exit program |
sys.path | Module search path |
sys.modules | Loaded modules cache |
sys.stdin/stdout/stderr | Standard streams |
sys.platform | OS identifier |
sys.version_info | Python version tuple |
sys.getsizeof() | Object size in bytes |
sys.executable | Python interpreter path |
sys.getrecursionlimit() | Max recursion depth |
The sys module connects your Python code to its runtime environment. Master it for robust, system-aware applications.
React to this post: