atexit function is not called when exiting the script using Ipython

余生长醉 提交于 2019-12-02 06:22:21

atexit functions are called when the Python interpreter exits, not when your script finishes. When you %run something in IPython, the interpreter is still running until you quit IPython. When you do that, you should see the output from your exit_function().

Possibly what you want is a try/finally, which ensures that the finally code is run after the try block, even if an exception occurs:

try:
    print("Doing things...")
    raise Exception("Something went wrong!")
finally:
    print("But this will still happen.")

If you really need to make atexit functions run, then you can call atexit._run_exitfuncs. However, this is undocumented, and it may do unexpected things, because anything can register atexit functions - IPython itself registers half a dozen, so you're likely to break things if you do it in IPython.

(Also, Python 2.4? For the sanity of developers everywhere, if it's possible to upgrade, do so ;-) )

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!