Monday, January 24, 2011

Exiting a Python program

You'd think this would be a straightforward topic, wouldn't you? In general it is simple, but there is a gotcha.

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

6 comments:

  1. Thanks! I couldn't find this anywhere.

    ReplyDelete
  2. If nothing catches the exception, then the python interpreter catches it at the end, does not print a stack trace, and then calls exit.

    ReplyDelete
  3. Thank you. Glad I found your article. This problem was a surprise to me when I recently encountered it.

    ReplyDelete
  4. Thats access protected variable, I guess.Is that possible to use outside function

    ReplyDelete
  5. Thanks - it is really help to the point.

    ReplyDelete
  6. Thank you so much for this article! After 45 minutes of searching Google, this was the one that helped! :)

    ReplyDelete