IPython:在ctrl + d keypress之后执行一个函数

时间:2016-11-21 17:30:55

标签: python ipython

我现在有一个django项目,我喜欢通过执行生成./manage.py shell shell的ipython来测试和检查事物。

在某些项目中,我有一个在后台运行并执行操作的线程。有时,在ipython会话中,我需要启动其中一个线程。我经常忘记join()线程之前我按ctrl+d退出shell,此时ipython阻止。

我尝试使用atexit.register注册一个清理方法,但由于调用太晚而无法正常工作。

import time
import atexit
from threading import Thread


def test():
    for x in xrange(30):
        print "x = %s" % x 
        time.sleep(1)

th = Thread(target = test)

def stop():
    global th
    print "ATEXIT: stop"
    if th.is_alive():
        th.join()

atexit.register(stop)

我把它放在test.py

文件中
$ ipython
In [1]: %run "test.py"

In [2]: ctrl+d pressed                                                                                                                                                      
ATEXIT: stop

如您所见,执行了atexit注册的功能。但是,如果我启动线程:

$ ipython
In [1]: %run "test.py"

In [2]: th.start()
x = 0
x = 1
....
In [3]: ctrl+d pressed 
x = 2
x = 3
.....
x = 29
ATEXIT: stop

所以,我需要的是按stop()后执行ctrl+d的方法。我找到了这个帖子Override ipython exit function - or add hooks in to it,但我不知道如何从交互式shell安装一个钩子,而且似乎已经弃用了该钩子。按ctrl+d后如何执行代码?

1 个答案:

答案 0 :(得分:0)

我在这里找到了(可能的)答案:How can I capture 'Ctrl-D' in python interactive console?

我不知道它与iPython有什么不同,但是Ctrl-D应该引发一个EOFError。试试这段代码:

try:
    raw_input()
except EOFError:
    pass

如果这对iPython不起作用,请告诉我。