Skip to content

Module 15 · Python Standard Libraries — topic 6 of 13

sys

The sys module: command-line arguments with sys.argv, exiting with sys.exit and exit codes, standard streams, the Python version, sys.path and sys.modules, and the recursion limit.

Beginner 8 min read·Lesson 227 of 306 in Python Programming

Learning objectives

  • Read command-line arguments
  • Exit with meaningful exit codes
  • Inspect the interpreter's version and settings

Definition

sys gives access to the Python interpreter itself: the arguments the program was started with, the standard input/output/error streams, the version, the module search path, loaded modules and interpreter settings.

Introduction

Command-line tools receive arguments, print errors separately from output, and report success or failure with an exit code. sys provides all three.

Why it matters

Well-behaved command-line programs follow these conventions, so they work with shells, scripts and automation tools.

Detailed explanation

sys.argv is a list: argv[0] is the script name and the rest are the arguments typed after it (all strings).

sys.exit(code) ends the program by raising SystemExit. Exit code 0 means success; non-zero means an error. sys.exit("message") prints the message to stderr and exits with code 1.

sys.stdin, sys.stdout and sys.stderr are the standard streams. Error messages should go to stderr: print(msg, file=sys.stderr).

sys.version and sys.version_info describe the running Python; compare with tuples: sys.version_info >= (3, 10).

sys.path is the module search path and sys.modules the cache of loaded modules (see Modules and Packages).

sys.getrecursionlimit() returns the maximum recursion depth (usually 1000).

For anything beyond a couple of arguments, use argparse, which builds on sys.argv and generates help messages.

Syntax

Python
import sys
if len(sys.argv) < 2:
print("usage: greet NAME", file=sys.stderr)
sys.exit(2)
print("Hello,", sys.argv[1])
  • argv holds arguments as strings.
  • exit codes signal success or failure.
  • Errors go to stderr.

Code examples

Interpreter information

Python
import sys
print(sys.version_info >= (3, 10), sys.version_info.major)
print(type(sys.argv).__name__)
Output
True 3
list

Streams and exiting

Python
import sys
n = sys.stdout.write("written directly\n")
print(n)
try:
sys.exit(3)
except SystemExit as e:
print("exit code:", e.code)
Output
written directly
17
exit code: 3

More examples

A tiny command-line program

Python
import sys
def main(argv):
if len(argv) < 2:
print("usage: greet NAME [TIMES]")
return 2
name = argv[1]
times = int(argv[2]) if len(argv) > 2 else 1
for _ in range(times):
print(f"Hello, {name}!")
return 0
print("exit", main(["greet.py", "Asha", "2"]))
print("exit", main(["greet.py"]))
print(sys.getrecursionlimit() >= 1000, "sys" in sys.modules)
Output
Hello, Asha!
Hello, Asha!
exit 0
usage: greet NAME [TIMES]
exit 2
True True

Step-by-step explanation

  • main receives the argument list instead of reading sys.argv directly, which makes it easy to test.
  • It returns an exit code; a real script would end with sys.exit(main(sys.argv)).
  • The usage message is printed to stdout here so the example output is visible; real tools send it to stderr.

Expected output

Running “A tiny command-line program” prints exactly:

TextOutput
Hello, Asha!
Hello, Asha!
exit 0
usage: greet NAME [TIMES]
exit 2
True True

Practical applications

  • Command-line utilities and automation scripts.
  • Checking the Python version before using new features.

Best practices

  • Return exit codes from main() and pass them to sys.exit.
  • Print errors to stderr.
  • Use argparse for real argument parsing.

Common mistakes

Forgetting argv items are strings

Avoid

times = sys.argv[2] * 2 # '33' not 6

Prefer

times = int(sys.argv[2]) * 2

Arguments arrive as text and must be converted.

Catching SystemExit by accident

Avoid

try:
main()
except BaseException:
pass

Prefer

try:
main()
except Exception as e:
log(e)

BaseException includes SystemExit, so the program can't exit properly.

Important notes

  • sys.stdin.read() reads all piped input, e.g. from python script.py < data.txt.

Key takeaways

  • sys.argv holds command-line arguments.
  • sys.exit(code) ends with an exit code.
  • sys exposes the version, streams, path and modules.

Try it yourself

  1. 1
    Write add.py that prints the sum of all numbers given as arguments.
  2. 2
    Make a script exit with code 1 and an error message on stderr when no file name is given.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is sys.argv[0]?
Practise this topic