Call sys.exit(0) (or raise SystemExit("Error message")) from the built-in sys module for clean script termination—because sys.exit() raises the SystemExit exception so finally blocks execute, context managers (with statements) close files/locks cleanly, and buffered stdout/stderr streams flush properly, whereas os._exit(1) kills the OS process instantaneously without cleanup and should be reserved strictly for os.fork() child processes or deadlocked threads.
Basic Example
import sys
def run_pipeline(data: list[int]) -> None:
if not data:
# 1. Recommended (Clean exit with non-zero status code & message to stderr):
sys.exit("Error: input dataset is empty.")
print(f"Processing {len(data)} records...")
# 2. Recommended (Clean exit with status code 0 for normal early completion):
sys.exit(0)
try:
run_pipeline([])
finally:
# Runs reliably when `sys.exit()` or `raise SystemExit` is called:
print("Cleanup: releasing resources before exit.")
Key Details & Edge Cases
- Exit status codes (
0vs. non-zero1–125vs. string messages):sys.exit()orsys.exit(0)signals success to the operating system shell ($?on Unix,ERRORLEVELon Windows).sys.exit(1)signals failure with exit code1.- Passing a string—
sys.exit("Fatal config error")—automatically prints the string tosys.stderrand exits with status code1.
- Why
sys.exit()does NOT terminate the process from inside a worker thread:sys.exit()raisesSystemExitonly in the thread that calls it. Inside athreading.Thread,SystemExitsilently terminates that single worker thread while the main thread and other non-daemon threads keep running. To terminate the entire multi-threaded process immediately from a worker thread when clean shutdown viathreading.Eventis impossible, callos._exit(1)(flushingsys.stdout.flush()andsys.stderr.flush()manually first).
- Avoid catching
SystemExitaccidentally with bareexcept:orexcept BaseException::SystemExitinherits fromBaseException(notException), so standardexcept Exception:blocks letsys.exit()propagate through cleanly. Never write a bareexcept:that swallows exceptions without re-raisingSystemExit, or your script will refuse to exit.
- Avoid
exit()andquit()in production scripts:- Built-in
exit()andquit()live in thesitemodule intended exclusively for the interactive REPL—they fail withNameErrorif Python is launched with-S(python -S script.py). Always usesys.exit()orraise SystemExit(...)in.pyfiles.
- Built-in
- Child processes created via
os.fork()(os._exit):- After
os.fork()on Unix/Linux, the child process must exit usingos._exit()rather thansys.exit(code)so the child does not run parentatexithandlers or double-flush sharedstdiobuffers.
- After
Comparison of Process Termination Methods in Python
| Method | Runs finally & with Cleanup? |
Flushes stdout / stderr Buffers? |
Stops Entire Process When Called From a Worker Thread? | Best Used When |
|---|---|---|---|---|
sys.exit(code) (Recommended) |
Yes | Yes | No (exits calling thread only) | Standard, clean termination from the main thread with an OS exit code (0 = OK, 1 = error). |
raise SystemExit(code) |
Yes | Yes | No (exits calling thread only) | Identical to sys.exit() without needing import sys (helpful for static type checkers). |
os._exit() |
No (immediate kernel exit) | No (must call .flush() manually first) |
Yes (kills entire process immediately) | Exiting os.fork() child processes or aborting a frozen/deadlocked multi-threaded process. |
exit() / quit() |
Yes | Yes | No | Interactive REPL sessions only; avoid in .py scripts (NameError under python -S). |
You must log in or register to comment.