os. _exit of and sys. exit of exit of 0 and exit of 1
- 2020-06-07 04:45:56
- OfStack
os. _exit() and sys. exit(), exit(0) and exit(1)
os. _exit () and sys exit ()
os._exit() vs sys.exit()
An overview of the
Python has two exits: os. _exit() and sys. exit(). This article introduces the differences and choices between the two approaches.
os. _exit() terminates the python program directly and all subsequent code will not continue to execute.
sys. exit() throws an exception: SystemExit, and if the exception is not caught, the python interpreter exits. If there is code to catch this exception, it will still execute. Catching this exception does a little extra cleanup. 0 is normal exit, other values (1-127) are abnormal, and abnormal events can be thrown for capture.
For example
#!/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')# Quit without printing
Output:
die
cleanup
The difference between
To sum up, the exit of sys.exit () is elegant, and the invocation throws an SystemExit exception, which can be caught and cleaned up. os. _exit() simply exits the python interpreter and the remaining statements are not executed.
1 Generally use ES56en. exit(), 1 generally use ES59en. _exit() in the subprocess of fork
os. _exit() is generally used to exit a thread
sys. exit() is used to exit in the main thread.
exit() should be the same as exit() for other languages such as C.
os. _exit() calls the _exit() function of the C language.
builtin. exit is an Quitter object whose call method throws an SystemExit exception.
exit (0) and exit (1)
exit(0) : Exit without error
exit(1) : Exit with error
The exit code tells the interpreter (or the operating system)
Thank you for reading, I hope to help you, thank you for your support to this site!