liveBook · Manning

Exit code

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

An error code is a numeric process exit status indicating that a program terminated because an error occurred.

An exit code is the numeric status a process returns when it stops. A value of 0 means success; any nonzero value signals an error to the operating system or calling program. section 9.3.3 section 17.1.2

Use exit codes to make command-line programs behave predictably:

  • Call sys.exit(1) after reporting a failure, or pass a string to print it to STDERR and exit with code 1. section 17.1.2
  • Send error messages to sys.stderr so shells can separate them from normal STDOUT output, for example with Bash redirection such as 2>err. section 9.3.3
  • Return nonzero status when validation fails, such as a missing placeholder, invalid integer, or argument below the permitted minimum. section 17.1 section 9.1.1
  • Test failure behavior by asserting that the returned status is not zero and that the diagnostic contains the expected message. section 9.1.1

Rejecting an invalid argument

if args.adjectives < 1: parser.print_usage() print(f'--adjectives "{args.adjectives}" must be > 0', file=sys.stderr) sys.exit(1) Running ./abuse.py -a -4 prints the usage and error message, then returns a nonzero exit code. A pipeline can use that status as a signal to stop the overall operation. section 9.3.3 section 9.1.1

if args.adjectives < 1:
    parser.print_usage()                                                     #1
    print(f'--adjectives "{args.adjectives}" must be > 0', file=sys.stderr)  #2
    sys.exit(1)                                                              #3

Inspect the complete validation branch that separates usage output, STDERR diagnostics, and the nonzero exit status. section 9.3.3

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

How deep it goes
Explains zero versus nonzero statuses, sys.exit() forms, STDERR routing, validation branches, and status assertions, but not operating-system status internals.
Examples
Demonstrates invalid arguments, missing placeholders, STDERR redirection, explicit sys.exit(1), string-based sys.exit(), and nonzero-status tests.
What it assumes
Assumes Python command-line programs and shell usage, while teaching status conventions, STDERR handling, and explicit validation from examples.
What you can do after
Apply it via Python's sys.exit() and argparse to report failures, separate diagnostics, stop pipelines, and test error behavior.
How it connects
Connects exit codes with sys.exit(), STDERR, STDOUT, argparse, command-line validation, testing, and pipelines.

Also explained in

Compare how 2 books explain exit code →

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.