Python sys.exit: set the exit status
sys.exit(n) ends the program with exit status n. sys.exit("text") prints the text to standard error and exits with status 1.
Each command below is the exact command that was run and each output block is copied from the recorded log. Test ids, log hashes and exit statuses are in the evidence table.
TE-86-A: sys.exit with an integer and with a string, read through the shell exit status
Setup for this run, inside a throwaway directory (mktemp -d):
printf 'import sys\nsys.exit(3)\n' > a.py
printf 'import sys\nsys.exit("bad")\n' > b.pyCommand:
python3 a.py; echo a=$?; python3 b.py 2>err.txt; echo b=$?; cat err.txtRecorded output:
a=3
b=1
badExit status: 0. The output matches the expected text written before the run.
TE-86-B: sys.exit raises SystemExit, which can be caught, and its code is the argument
Setup for this run, inside a throwaway directory (mktemp -d):
cat > s.py <<'EOS'
import sys
try:
sys.exit(4)
except SystemExit as e:
print(e.code)
print('after')
EOSCommand:
python3 s.pyRecorded output:
4
afterExit status: 0. This status and the output match what was written before the run.
TE-86-C: expected non-zero exit: sys.exit(5) after a print keeps the printed text and ends with exit status 5
Setup for this run, inside a throwaway directory (mktemp -d):
cat > s.py <<'EOS'
import sys
print('before')
sys.exit(5)
print('after')
EOSCommand:
python3 s.pyRecorded output:
beforeExit status: 5. This status and the output match what was written before the run.
TE-86-B: sys.exit(4) was caught as SystemExit, e.code printed 4, and the line after the try block still ran. TE-86-C: before was printed, then sys.exit(5) ended the program with exit status 5. The line after it did not run, and standard error was empty.
Limits
The docs say: any other object is printed to stderr and results in an exit code of 1. Only integer and string arguments were run. TE-86-B catches SystemExit once and reads its code.
Source
Evidence table
| Test | What it checks | Exit | Verdict | Log sha256 (first 12) | |---|---|---|---|---| | TE-86-A | sys.exit with an integer and with a string, read through the shell exit status | 0 | PASS | 2e6187749e77 | | TE-86-B | sys.exit raises SystemExit, which can be caught, and its code is the argument | 0 | PASS | 62b9525f8e96 | | TE-86-C | expected non-zero exit: sys.exit(5) after a print keeps the printed text and ends with exit status 5 | 5 | PASS | 732bd277e8c2 |
Recorded on: bash 5.1.16(1)-release; git version 2.34.1; Python 3.10.12. Locale C.UTF-8, TZ=UTC. Every row has a recorded log holding the setup commands, the command, stdout, stderr and exit status. The first 12 characters of the log's sha256 are in the table.
All full guides: All guides