Os._exit () and Sys.exit ()
Os._exit () vs Sys.exit ()
Overview
Python's program has two exit methods: Os._exit (), Sys.exit (). This article describes the differences and choices between the two approaches.
Os._exit () will terminate the Python program directly, and all subsequent code will not continue to execute.
Sys.exit () throws an exception: Systemexit, if the exception is not captured, the Python interpreter exits. If there is code to catch this exception, the code will still execute. Catching this exception can do some extra cleanup work. 0 for normal exit, other values (1-127) are not normal, can throw abnormal events for capture.
#! / usr / local / bin / env python
import os, sys
try:
sys.exit (0)
except:
print (‘die’)
finally:
print (‘cleanup’)
try:
os._exit (0)
except:
print (‘die’)
print (‘os.exit’) # Exit without printing
Die
Cleanup
Difference
In summary, the exit of Sys.exit () is more elegant, after the call will throw a Systemexit exception, you can catch this exception to do cleanup work. Os._exit () exits the Python interpreter directly, and the remaining statements are not executed.
Generally use sys.exit (), generally in the fork out of the sub-process using Os._exit ()
generally os._exit () is used to exit in the thread
Sys.exit () is used to exit from the main thread.
Exit () should be the same as exit () in other languages such as C language.
Os._exit () invokes the C-language _exit () function.
builtin. Exit is a quitter object, and the call method of this object throws a Systemexit exception.
Exit (0) and exit (1)
Exit (0): no error exits
Exit (1): There was an error exiting
The exit code tells the interpreter (or the operating system)
Usage and differences of os._exit () and Sys.exit (), exit (0) and exit (1) in Python