Programmatically stop execution of python script?
To immediately halt a Python script, use sys.exit() from the sys module, which triggers a SystemExit exception. For more abrupt termination without any cleanup, there's os._exit(), yet it's a last resort. Below is the direct usage example of sys.exit():
In most cases, you'll want to use sys.exit() for elegant exits.
Stop script the standard way with sys.exit()
Graceful exit with sys.exit()
For normal termination, use sys.exit(). This is handy after completing all procedures, or running into a fatal error. You can supply exit codes optionally to show script's success (0) or failure (non-zero):
Raising the white flag with SystemExit
You can also politely ask the script to halt by raising the SystemExit exception using raise SystemExit(0):
Going commando with exit() and quit()
Beyond sys.exit(), exit() and quit() are built-ins designed for interactive use, yet you can utilize these in scripts too. Yet, they're less desirable in production-grade code:
Going out with a bang with non-zero exits
You can make a Python script go kaput by passing a non-zero argument indicating the error to sys.exit() when it hits a roadblock:
Handling exceptions like a pro
Don't catch SystemExit unless you mean it
Avoid catching the SystemExit exception unless specifically intending to handle it, like logging or cleanup. An accidental catch may prevent the script from exiting:
Mastering exception handling
Use try/except blocks diligently. Catch just the exceptions that you're equipped to handle, allowing SystemExit and KeyboardInterrupt to pass through:
Exit strategies for diverse scenarios
Abrupt exit with os._exit()
When cleanup isn't required or poses risk, os._exit() can help you bolt immediately. It's the perfect escape pod for quick termination:
Stopping long processes with signals
Use signal handling with Python's signal module, ideal for long-running processes that need external prompts to quit:
Time-bound script termination
Use sched or threading.Timer for timer-based termination:
Was this article helpful?