← Back to Python Course | Chapter 12: Standard Library | Lesson 2 of 9

Python sys Module

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

python
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

python
import sys

try:
    print("Before exit")
    sys.exit(0)
finally:
    print("Cleanup still runs")

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

python
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

python
import sys
sys.stderr.write("This is an error message\n")
print("This is normal output")

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

python
import sys
print(sys.version_info.major)
print(sys.version_info >= (3, 0))

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.