Python sys Module
In this page:
import sys
sys.argv
sys.exit(code)
sys.path
Command-Line Arguments
The sys module exposes low-level details of the running Python interpreter itself, distinct from os's operating-system-level operations.
sys.argv is a list where index 0 is always the script's own filename and the following entries are whatever arguments were typed after it on the command line.
Example: Command-Line Arguments
import sys
print(sys.argv[0])
Exiting Programs Safely
sys.exit() immediately terminates the running program, optionally accepting an integer exit code that other programs or shell scripts can check -- conventionally 0 for success and any non-zero value to signal an error occurred.
It works by raising a SystemExit exception internally, so surrounding try/finally blocks still run their cleanup code.
Example: Exiting Programs Safely
import sys
try:
print("Before exit")
sys.exit(0) # raises SystemExit with code 0
finally:
print("Cleanup still runs") # finally runs even though sys.exit() was called
Inspecting System Paths
sys.path is the list of directories Python searches, in order, when resolving an import statement, starting with the script's own directory.
Prepending a custom directory to this list at runtime is a common (if somewhat hacky) way to make Python find modules that live outside the normal installed-package locations.
Example: Inspecting System Paths
import sys
print(len(sys.path) > 0)
Standard Inputs and Outputs
sys.stdin, sys.stdout, and sys.stderr are file-like objects representing the process's standard input, output, and error streams respectively.
Writing to sys.stderr directly is useful for error or diagnostic messages you want to keep separate from a program's normal stdout output, which matters when output is piped or redirected.
Example: Standard Inputs and Outputs
import sys
sys.stderr.write("This is an error message\n") # goes to the error stream, separate from stdout
print("This is normal output") # goes to stdout
Python Version Information
sys.version gives a human-readable string describing the interpreter version and build details, while sys.version_info gives the same information as a structured, comparable tuple like (3, 11, 4).
Checking sys.version_info is the reliable way to guard version-specific code paths, since string comparison on sys.version sorts incorrectly once you hit double-digit version numbers.
Example: Python Version Information
import sys
print(sys.version_info.major) # major version number as an int
print(sys.version_info >= (3, 0)) # tuple comparison works correctly, unlike comparing version strings
- Using
sys.argv[1]without checking its length, which raisesIndexErrorwhen no argument is given. - Forgetting that
sys.argv[0]is the script name, so your first argument is at index 1. - Forgetting that
sys.argvvalues are strings, sosys.argv[1] + 1fails until you convert withint().
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: