When you want to exit a program written in python, the typical way to do it is to call sys.exit(status) like so:
import sys
sys.exit(0)
For simple programs, this works great; as far as the python code is concerned, control leaves the interpreter right at the sys.exit method call. If you look under the hood, though, sys.exit is a little more interesting. It does not immediately call the libc function exit(), but instead raises a SystemExit[1] exception. If nothing catches the exception, then the python interpreter catches it at the end, does not print a stack trace, and then calls exit.There are situations in which you do not want to raise an exception to exit the program. The example I recently came across was debugging some of my python code in Oz[2]. Oz is careful to clean up after itself, which means that on many exceptions it catches the exception, does some cleanup steps, and then re-raises the exception. In general this is a good thing to do, but sometimes when debugging I want to totally skip the cleanup steps so I can examine what went wrong.
Enter os._exit(). This function is a thin wrapper around the libc function exit(), so it does not raise an exception and leaves the program immediately. You would use it like:
import os
os._exit(1)
[1] http://docs.python.org/library/exceptions.html
[2] http://www.aeolusproject.org/oz.html
Thanks! I couldn't find this anywhere.
ReplyDeleteIf nothing catches the exception, then the python interpreter catches it at the end, does not print a stack trace, and then calls exit.
ReplyDeleteThank you. Glad I found your article. This problem was a surprise to me when I recently encountered it.
ReplyDeleteThats access protected variable, I guess.Is that possible to use outside function
ReplyDeleteThanks - it is really help to the point.
ReplyDeleteThank you so much for this article! After 45 minutes of searching Google, this was the one that helped! :)
ReplyDeleteprint from the script do not seem to hit stdout when os._exit() is called !! probably an explicit flush is required prior to exit.
ReplyDeleteThanks a lot!
ReplyDeleteThank You. Although, doing it with Python in Visual Studio 17,
ReplyDeleteWith sys.exit(0) It was throwing an unhandeled exception error.
With os._exit(1), it is showing the pop-up: 'Debugger exited unexpectedly',
I am just commenting to let you know of the perfect experience my wife's princess encountered studying your web site. She picked up numerous details, most notably what it's like to have an ideal helping character to have many more very easily gain knowledge of selected advanced subject matter. You undoubtedly exceeded our own expectations. Thanks for offering such effective, healthy, explanatory and in addition fun thoughts on this topic to Gloria. https://python.engineering/python-subtraction-of-dictionaries/
ReplyDelete