@MZeeshanM to PythonEnglish • 3 days ago

How do you stop a running Python script immediately from inside code?

message-square
0
1
How do you stop a running Python script immediately from inside code?
@MZeeshanM to PythonEnglish • 3 days ago

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 (0 vs. non-zero 1–125 vs. string messages):
    • sys.exit() or sys.exit(0) signals success to the operating system shell ($? on Unix, %ERRORLEVEL% on Windows).
    • sys.exit(1) signals failure with exit code 1.
    • Passing a string—sys.exit("Fatal config error")—automatically prints the string to sys.stderr and exits with status code 1.
  • Why sys.exit() does NOT terminate the process from inside a worker thread:
    • sys.exit() raises SystemExit only in the thread that calls it. Inside a threading.Thread, SystemExit silently 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 via threading.Event is impossible, call os._exit(1) (flushing sys.stdout.flush() and sys.stderr.flush() manually first).
  • Avoid catching SystemExit accidentally with bare except: or except BaseException::
    • SystemExit inherits from BaseException (not Exception), so standard except Exception: blocks let sys.exit() propagate through cleanly. Never write a bare except: that swallows exceptions without re-raising SystemExit, or your script will refuse to exit.
  • Avoid exit() and quit() in production scripts:
    • Built-in exit() and quit() live in the site module intended exclusively for the interactive REPL—they fail with NameError if Python is launched with -S (python -S script.py). Always use sys.exit() or raise SystemExit(...) in .py files.
  • Child processes created via os.fork() (os._exit):
    • After os.fork() on Unix/Linux, the child process must exit using os._exit(code) rather than sys.exit(code) so the child does not run parent atexit handlers or double-flush shared stdio buffers.

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(code) 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).