Python Sys Module

The sys module gives access to Python runtime details such as command-line arguments, the import path, and the current interpreter version.

import sys

Use sys when your code needs to talk to the Python interpreter itself, not just to your own application objects.

Command-line arguments

sys.argv is a list of arguments passed to the current script.

import sys

sys.argv = ['main.py', '--debug', 'app']
print(sys.argv[0])
print(sys.argv[1:])
main.py
['--debug', 'app']

For real command-line applications, prefer argparse. It builds on the same idea but gives you validation and help messages.

Python version

import sys

print(sys.version_info.major)
print(sys.version_info.minor)
3
14

Import search path

sys.path controls where Python looks for modules.

import sys

print(type(sys.path).__name__)
print(len(sys.path) > 0)
list
True

The first entries in sys.path usually include your current project, which is why local modules can be imported.

Standard input and output

sys.stdin, sys.stdout, and sys.stderr are file-like objects used by the interpreter.

import sys

print(sys.stdout.writable())
print(sys.stderr.writable())
True
True

Exiting a program

import sys

try:
    sys.exit(0)
except SystemExit as exc:
    print(exc.code)
0