liveBook · Manning

Sys.exit

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

sys.exit() is a Python function that terminates the current program and supplies an exit status or error message.

Use sys.exit() to halt a Python program and report whether it completed successfully. With no argument, it exits with status 0, meaning zero errors. section 9.3.3 section 17.0

Choose the argument according to the result you need to communicate:

  • Call sys.exit(1), or use another nonzero integer, to signal failure to the operating system or a calling program. section 17.1.2
  • Call sys.exit('message') to print the message to STDERR and exit with status 1 automatically. section 17.5
  • Use STDERR for errors so shells can redirect diagnostics separately from normal STDOUT output. section 9.3.3

Reject invalid command-line input

if args.adjectives < 1: parser.print_usage() print(f'--adjectives "{args.adjectives}" must be > 0', file=sys.stderr) sys.exit(1) This prints usage information, sends a diagnostic to STDERR, and stops before the program continues with invalid data. section 9.3.3

>>> import sys
>>> sys.exit('You gross, thin-faced worm!')
You gross, thin-faced worm!

Inspect the shortest form that prints an error message and terminates the program. section 9.3.3

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Explains integer and string forms, STDERR behavior, and redirection, but does not detail exception mechanics.
Examples
Demonstrates invalid command-line arguments, missing regular-expression placeholders, bad CSV inputs, and redirected error output.
What it assumes
Uses Python imports, functions, command-line arguments, file streams, and basic shell commands without developing those concepts here.
What you can do after
Diagnose/debug with it by stopping invalid-input paths and exposing clear nonzero statuses and STDERR messages.
How it connects
Connects exit status with STDERR, STDOUT, command pipelines, argument validation, and unit testing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.