The sys Module
The sys module provides access to system-specific parameters and functions, allowing interaction with the interpreter and environment.
python import sys
1. Getting Command-Line Arguments (sys.argv)
sys.argv is a list containing the command-line arguments passed to the script. The first element (sys.argv[0]) is always the name of the script itself.
Example Script (process.py):
python
process.py
if len(sys.argv) > 1: filename = sys.argv[1] print(f"Processing file: {filename}") else: print("No filename provided.")
Running the script:
bash python process.py configuration.json
Output: Processing file: configuration.json
2. Exiting the Program (sys.exit)
Used to exit the Python interpreter immediately.
python if not os.path.exists('critical_file.txt'): print("FATAL: Critical file missing. Exiting.") sys.exit(1) # Exit code 1 indicates an error
3. Interpreter Information
python print(f"Python Version: {sys.version}") print(f"Search Path for Modules: {sys.path}")