Sys Module
The sys module gives you direct access to variables and functions that interact closely with the Python interpreter itself, such as command-line arguments, system-specific settings, and controlling how a program exits.
Accessing Command-Line Arguments
When a Python script is run from the terminal with extra arguments, sys.argv captures them as a list, with the first item always being the script's own name.
# script.py
import sys
print(sys.argv)
# Running: python script.py hello 123
# Output: ['script.py', 'hello', '123']
Other Useful sys Features
sys.exit()- immediately stops the program, optionally with an exit status codesys.version- returns the current Python interpreter's version as a stringsys.path- a list of directories Python searches through when importing modulessys.platform- identifies the operating system the script is running on
import sys
print(sys.version) # e.g. 3.12.1
print(sys.platform) # e.g. 'linux', 'win32', 'darwin'
if len(sys.argv) < 2:
print("Missing required argument")
sys.exit(1)
The sys module is especially useful when writing command-line tools and scripts that need to behave differently based on how they were invoked, or that need to exit cleanly with a specific status code for automation pipelines.
Coming Up Next
Next, you'll take a closer look at some of Python's most commonly used built-in modules, starting with the os module for working with files and directories.