Python Tutorial › Modules › sys Module

Python sys Module

IntermediateLesson 39 of 479 min read6 runnable examples

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.

Advertisement
In this lesson
  • 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.

greet.py
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)
Terminal
$ python greet.py Asha 2script: greet.pyarguments: ['Asha', '2']Hello, AshaHello, Asha$ python greet.pyscript: greet.pyarguments: []
Tip

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.

check.py
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:])
Terminal
$ 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: 2

Version and platform

Python
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)
Output
3 15
True
win32
True

Use a version check to fail early with a clear message:

Python
import sys if sys.version_info < (3, 10):    sys.exit("This script needs Python 3.10 or newer")print("version OK")
Output
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.

Python
import sys print(type(sys.path).__name__, len(sys.path) > 2)print(any(p.endswith("site-packages") for p in sys.path))
Output
list True
True
Note

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.

Python
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"))
Output
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:

Python
import sys numbers = [int(line) for line in sys.stdin if line.strip()]print("sum:", sum(numbers))
Outputtyped input: 5, 10, 15
sum: 30

Other useful sys features

Python
import sys print(sys.getrecursionlimit())print(sys.getsizeof([]) < sys.getsizeof([1, 2, 3]))print(sys.executable.endswith(("python.exe", "python", "python3")))
Output
1000
True
True

Check your understanding

Quick quiz

1. What is sys.argv[0]?

2. What type are the values in sys.argv?

3. Which exit code means success?

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.

Input
python add.py 3 4.5 10
Expected output
sum = 17.5
Hint 1

Wrap the conversion in try/except ValueError and call sys.exit(1) on failure.

Program Practice

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):.

Leave a Comment