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
