sys
The Python sys
module provides access to system-specific parameters and functions. It allows you to interact with the Python runtime environment and the underlying operating system.
Here’s a quick example:
>>> import sys
>>> sys.version
'3.13.2 (main, Feb 24 2025, 22:41:48) [Clang 16.0.0 (clang-1600.0.26.6)]'
Key Features
- Accesses command-line arguments passed to Python scripts
- Allows interaction with the Python interpreter
- Provides tools to inspect and control the Python runtime
- Provides access to standard input, output, and error streams
- Provides introspection helpers
Frequently Used Classes and Functions
Object | Type | Description |
---|---|---|
sys.argv |
List | Grabs command-line arguments passed to the script |
sys.exit() |
Function | Exits from Python with an optional exit status |
sys.path |
List | Contains directories that the interpreter will search for modules |
sys.version |
str |
Holds the Python interpreter version information |
sys.stdin |
File-like object | References the standard input stream |
sys.stdout |
File-like object | References the standard output stream |
sys.stderr |
File-like object | References the standard error stream |
Examples
Access command-line arguments:
>>> import sys
>>> sys.argv
['script.py', 'arg1', 'arg2']
Exit the Python interpreter:
>>> import sys
>>> sys.exit(0)
Displays the Python version:
>>> import sys
>>> sys.version
'3.13.2 (main, Feb 24 2025, 22:41:48) [Clang 16.0.0 (clang-1600.0.26.6)]'
Common Use Cases
- Accessing and processing command-line arguments
- Managing the Python path for module imports
- Redirecting standard input, output, and error streams
- Exiting a program with a specific status code
- Introspecting Python code
Real-World Example
Suppose you want to access command-line arguments passed to a Python script. You can do this with sys.argv
:
script.py
import sys
if len(sys.argv) > 1:
print("Arguments passed to the script:")
for arg in sys.argv[1:]:
print(arg)
else:
print("No arguments provided.")
This script checks for command-line arguments and prints them, demonstrating how to use sys
to handle command‑line input.
Here’s how the script works:
$ python script.py apple banana cherry
Arguments passed to the script:
apple
banana
cherry
Related Resources
Tutorial
Python Command-Line Arguments
Python command-line arguments are the key to converting your programs into useful and enticing tools that are ready to be used in the terminal of your operating system. In this step-by-step tutorial, you'll learn their origins, standards, and basics, and how to implement them in your program.
For additional information on related topics, take a look at the following resources:
By Leodanis Pozo Ramos • Updated July 23, 2025