Python sys Module
The sys module gives your program access to the Python interpreter itself: the command-line arguments it was started with, the version and platform, where it looks for modules, and the standard input and output streams.
- Read command-line arguments with sys.argv
- Stop a program with sys.exit and an exit code
- Inspect the Python version and module search path
- Write to stdout and stderr
Command-line arguments: sys.argv
sys.argv is a list of the words typed after python. Item 0 is the script name, and the rest are the arguments, always as strings.
import sys print("script:", sys.argv[0])print("arguments:", sys.argv[1:]) if len(sys.argv) > 1: name = sys.argv[1] times = int(sys.argv[2]) if len(sys.argv) > 2 else 1 for _ in range(times): print("Hello,", name)$ python greet.py Asha 2script: greet.pyarguments: ['Asha', '2']Hello, AshaHello, Asha$ python greet.pyscript: greet.pyarguments: []For real command-line tools, use the argparse module. It builds --help output, converts types and reports missing arguments for you.
Exit with a status code: sys.exit
sys.exit() stops the program. By convention, exit code 0 means success and anything else means failure; CI systems and shell scripts check this code.
import sys def main(values): if not values: print("no values given", file=sys.stderr) sys.exit(2) print("total:", sum(map(int, values))) main(sys.argv[1:])$ python check.py 4 5 6total: 15$ python check.pyno values given$ python -c "import subprocess, sys; print('exit code:', subprocess.run([sys.executable, 'check.py']).returncode)"no values givenexit code: 2Version and platform
import sys print(sys.version_info.major, sys.version_info.minor)print(sys.version_info >= (3, 10))print(sys.platform)print(sys.maxsize == 2 ** 63 - 1)3 15 True win32 True
Use a version check to fail early with a clear message:
import sys if sys.version_info < (3, 10): sys.exit("This script needs Python 3.10 or newer")print("version OK")version OK
Where Python looks for modules: sys.path
import searches the folders in sys.path, in order: the script’s folder first, then the standard library, then installed packages.
import sys print(type(sys.path).__name__, len(sys.path) > 2)print(any(p.endswith("site-packages") for p in sys.path))list True True
A ModuleNotFoundError means none of these folders contains the module. Usually the package was installed into a different Python or virtual environment; see Modules & pip.
stdin, stdout and stderr
print() writes to sys.stdout. Error messages belong on sys.stderr, so they stay visible even when normal output is redirected to a file.
import sys sys.stdout.write("normal output\n")print("also normal output", file=sys.stdout)print("number of bytes written:", sys.stdout.write("abc\n"))normal output also normal output abc number of bytes written: 4
Reading all input lines from sys.stdin is the fastest way to read large input, which is common in coding challenges:
import sys numbers = [int(line) for line in sys.stdin if line.strip()]print("sum:", sum(numbers))sum: 30
Other useful sys features
import sys print(sys.getrecursionlimit())print(sys.getsizeof([]) < sys.getsizeof([1, 2, 3]))print(sys.executable.endswith(("python.exe", "python", "python3")))1000 True True
Check your understanding
Quick quiz
1. What is sys.argv[0]?
User arguments start at index 1.
2. What type are the values in sys.argv?
Convert them yourself, for example with int().
3. Which exit code means success?
Any non-zero code signals an error to the shell or CI.
Exercise: sum the arguments
Write add.py that prints the sum of all numbers passed on the command line, or exits with code 1 and a message if any argument is not a number.
python add.py 3 4.5 10
sum = 17.5
Hint 1
Wrap the conversion in try/except ValueError and call sys.exit(1) on failure.
import sys args = sys.argv[1:] or ["3", "4.5", "10"] # sample values when run without argumentstry: numbers = [float(a) for a in args]except ValueError as e: print("Error:", e, file=sys.stderr) sys.exit(1)print("sum =", sum(numbers))sum = 17.5
sys.argv[1:] skips the script name. Converting inside try means one bad argument stops the program with a clear message and a non-zero exit code.
Program Practice
20 Python sys Module Programs
Every program has a step-by-step explanation, colour-coded code and its real output.
Python sys module FAQ
How do I read command-line arguments in Python?
Use sys.argv, a list of strings where sys.argv[1:] are the arguments. For anything beyond a couple of arguments, use argparse.
What is the difference between sys.exit() and exit()?
exit() is a convenience for the interactive shell. Use sys.exit() in scripts; it raises SystemExit, which can carry an exit code or message.
How do I check the Python version in code?
Compare sys.version_info with a tuple: if sys.version_info >= (3, 10):.