Usage and differences of os._exit () and Sys.exit (), exit (0) and exit (1) in Python

Source: Internet
Author: User
Tags exit in


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


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.