I have right now a django
project and I like to test and check things by executing ./manage.py shell
which spawns an ipython
shell.
In some projects I have a threads that run in the background and do stuff. Sometimes, while in a ipython
session, I need to start one of these threads. I usually forget to join()
the thread before I press ctrl+d
to exit the shell, at which point ipython
blocks.
I tried registering a cleanup method with atexit.register
but that didn't work because it is called too late.
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)
I put that in a file test.py
$ ipython
In [1]: %run "test.py"
In [2]: ctrl+d pressed
ATEXIT: stop
As you can see the function registered with atexit
was executed. However, if I start the thread:
$ 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
So, what I need is a way of executing stop()
after I press ctrl+d
. I've found this thread Override ipython exit function - or add hooks in to it but I don't know how to install a hook from an interactive shell and besides, it seems that the hook has been deprecated. How can I execute code after pressing ctrl+d
?