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

