使用Ipython退出脚本时不调用atexit函数 [英] atexit function is not called when exiting the script using Ipython

查看:167
本文介绍了使用Ipython退出脚本时不调用atexit函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是用脚本写的代码,例如test_atexit.py

Below is the code written in a script say test_atexit.py

def exit_function():
    print "I am in exit function"
import atexit
atexit.register(exit_function)
print "I am in main function"

当我使用python2.4运行函数时,调用exit_function

When i run the function using python2.4 then exit_function is being called

$python2.4 test_atexit.py  
I am in main function  
I am in exit function

当我使用ipython运行相同时,则不调用exit_function

When i run the same using ipython then exit_function is not being called

$ ipython  
In [1]: %run test_atexit.py  
I am in main function  
In [2]: 

为什么在使用Ipython运行脚本时不调用exit_function以及如何让ipython调用exit_function

why exit_function is not called when running script using Ipython and how can i make ipython to call exit_function

推荐答案

atexit 函数在Python解释器退出时调用,而不是在脚本完成时调用。当您在IPython中%运行时,解释器仍在运行,直到您退出IPython。当你这样做时,你应该看到 exit_function()的输出。

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().

可能你想要的是一个try / finally,它确保在try块之后运行finally代码,即使发生异常:

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.")

如果你真的需要运行atexit函数,那么你可以调用 atexit._run_exitfuncs 。然而,这是没有记录的,它可能会做出意想不到的事情,因为任何东西都可以注册atexit函数 - IPython本身就会注册6个,所以如果你在IPython中这样做,你很可能会破坏它。

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.

(另外,Python 2.4?对于各地开发人员的理智,如果可以升级,请这样做;-))

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

这篇关于使用Ipython退出脚本时不调用atexit函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆