Home >Backend Development >Python Tutorial >How Do I Gracefully or Forcefully Terminate a Python Script?
Terminating a Script in Python
When faced with the need to exit a Python script prematurely, similar to PHP's die() function, developers can utilize sys.exit().
Implementation:
To invoke sys.exit(), simply import the sys module and execute sys.exit().
import sys sys.exit()
Sys Module Documentation:
According to the documentation for the sys module:
sys.exit([arg]) Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.
Usage:
The optional arg parameter can either be an integer (the script's exit status) or any other object. By default, the exit status is zero, indicating successful termination. Non-zero exit status denotes abnormal termination.
Using sys.exit() with a string error message is a convenient alternative for immediate script termination in the event of an error, such as sys.exit("some error message").
Note:
It's important to highlight that sys.exit()'s "nice" exit behavior applies only when invoked from the main thread. The interpreter cannot perform any cleanup if the exception is intercepted.
While sys.exit() effectively terminates the process from the main thread, it leaves running threads unaffected. For an immediate and complete kill of all threads and processes, os._exit(*errorcode*) provides a "hard exit" (compatibility may vary across operating systems).
The above is the detailed content of How Do I Gracefully or Forcefully Terminate a Python Script?. For more information, please follow other related articles on the PHP Chinese website!