sys

Access to the interpreter: command-line arguments, ending the program, the Python version, and streams.

On this page

Example

#
Python
import sys

if len(sys.argv) < 2:
    print("Usage: python greeting.py NAME")
    sys.exit(1)

name = sys.argv[1]
print(f"Hello, {name}!")
print(sys.argv)
Result
Hello, Emma!
['greeting.py', 'Emma']

The result for the command python greeting.py Emma. Run without an argument, the program prints the usage instructions and exits with code 1.

Definition and usage

#

The sys module gives access to information and settings of the Python interpreter itself. The most commonly used parts are the sys.argv list of command-line arguments and the sys.exit() function, which ends the program with a given exit code.

sys.argv[0] is the name of the script being run, and the following items are the arguments typed after it, always as strings. An exit code of 0 means success, and any other number means an error. It is read by shell scripts and tools that run your program.

The module also provides the standard streams sys.stdin, sys.stdout, and sys.stderr, the interpreter version in sys.version_info, the system name in sys.platform, and the list of directories searched on import in sys.path.

Syntax

#
Syntax
import sys

sys.argv
sys.exit(code)
sys.version_info
sys.stderr

More examples

#
The Python version and the recursion limit
Python
import sys

if sys.version_info >= (3, 10):
    print("The Python version is sufficient")
else:
    print("This program requires Python 3.10 or newer")

print(sys.version_info.major)
print(sys.getrecursionlimit())
Resultsaved result, you can check it
The Python version is sufficient
3
1000

getrecursionlimit() returns the maximum depth of recursive calls, 1000 by default.

Errors on stderr and the exit code
Python
import sys

def fail(message):
    print(f"Error: {message}", file=sys.stderr)
    sys.exit(1)

print("Loading data...")
fail("missing file course.json")
print("This line will not run")
Resultsaved result, you can check it
Loading data...
Error: missing file course.json

The second line goes to the error stream (stderr), so redirecting with python app.py > log.txt will write only the first one to the file. The program exits with code 1.

Good practices

#
  • For elaborate command-line arguments, with options and automatic help, use the argparse module instead of reading sys.argv by hand.
  • Arguments in sys.argv are strings. Convert numbers with int() and handle an invalid value.
  • Print error messages to sys.stderr, so they do not get mixed up with the programโ€™s actual output.

Related entries

#

Practise it in lessons

#

Spotted a mistake or missing an example? Write to us.