sys.argv / sys.exit() / sys.path
| Since: | Python 2(2000) |
|---|
Attributes and functions of the sys module, which manages command-line arguments, script termination, and module search paths.
Syntax
import sys # List of command-line arguments (index 0 is the script name) sys.argv # Exits the script (you can specify an exit code) sys.exit(0) # Normal exit sys.exit(1) # Error exit # List of directories searched for modules sys.path # Python version string sys.version # Platform identifier of the runtime environment sys.platform
Attributes and Functions
| Attribute / Function | Description |
|---|---|
| sys.argv | A list of command-line argument strings. sys.argv[0] is the script name; subsequent elements are the arguments passed by the user. |
| sys.exit(code) | Exits the script. An exit code of 0 indicates success; a value of 1 or greater indicates an error. |
| sys.path | A list of directories that Python searches for modules. You can add a path to this list to make your own modules importable. |
| sys.version | Returns version information about the running Python interpreter as a string. |
| sys.version_info | Returns version information as a named tuple. Useful for comparing version numbers. |
| sys.platform | Returns a string identifying the runtime platform (e.g., 'linux', 'darwin', 'win32'). |
| sys.stdin / sys.stdout / sys.stderr | File objects for standard input, standard output, and standard error. |
Sample Code
sys_argv_basic.py
import sys print(sys.argv[0]) print(sys.argv[1]) print(sys.argv[2]) print(len(sys.argv))
Running the code produces the following output:
python3 sys_argv_basic.py hello 42 sys_argv_basic.py hello 42 3
sys_argv_validate.py
import sys
if len(sys.argv) < 3:
print('Usage: python3 sys_argv_validate.py <name> <age>', file=sys.stderr)
sys.exit(1)
name = sys.argv[1]
age = int(sys.argv[2])
print(f'Name: {name}, Age: {age}')
Running the code produces the following output:
python3 sys_argv_validate.py Usage: python3 sys_argv_validate.py <name> <age>
Running the code produces the following output:
python3 sys_argv_validate.py "Light Yagami" 17 Name: Light Yagami, Age: 17
sys_info.py
import sys
print(sys.version)
if sys.version_info >= (3, 10):
print('Python 3.10 or later: match statements are available.')
if sys.platform == 'win32':
print('Running on Windows.')
elif sys.platform == 'darwin':
print('Running on macOS.')
else:
print('Running on Linux.')
print('An error occurred.', file=sys.stderr)
Running the code produces the following output:
python3 sys_info.py 3.12.4 (main, Jun 6 2024, 18:26:44) Python 3.10 or later: match statements are available. Running on macOS.
Common Mistakes
Common Mistake 1: Accessing arguments without checking the count
Accessing sys.argv[1] without checking whether any arguments were passed will raise an IndexError when the script is run without arguments. Check the argument count first or use try/except.
import sys
filename = sys.argv[1]
print(f'File: {filename}')
The same logic can also be written as:
import sys
if len(sys.argv) < 2:
print('Usage: python3 mistake1_ok.py <filename>', file=sys.stderr)
sys.exit(1)
filename = sys.argv[1]
print(f'File: {filename}')
Common Mistake 2: Using arguments as numbers without converting
All command-line arguments are stored as strings. You can convert them with int() or float() when a numeric value is needed. Using a string argument directly in arithmetic raises a TypeError.
import sys score = sys.argv[1] print(score + 10)
The same logic can also be written as:
import sys score = int(sys.argv[1]) print(score + 10)
Notes
sys.argv is the fundamental mechanism for passing arguments to a script from the command line. All arguments are stored as strings, so you can convert them with int() or float() when numeric values are needed. For more complex argument parsing, the standard library's argparse module lets you implement automatic help messages, type conversion, and optional arguments.
sys.exit() internally raises a SystemExit exception, which means it can be caught with try/except. In most cases, however, you can write logic to let it propagate and terminate the script. Exit codes are used by shell scripts and CI/CD systems to determine success or failure. Always exit with a non-zero code when an error occurs.
For reading environment variables, see os.environ / os.getenv().
If you find any errors or copyright issues, please contact us.