0

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?

Community
  • 1
  • 1
Pablo
  • 13,271
  • 4
  • 39
  • 59
  • http://stackoverflow.com/questions/18114560/python-catch-ctrl-c-command-prompt-really-want-to-quit-y-n-resume-executi This probably answers your question. – Douglas Nov 21 '16 at 18:07
  • @Douglas: I'll take a closer look later, thanks. – Pablo Nov 21 '16 at 18:53
  • @Douglas: not exactly what I'm looking for. I want to execute some code when I press `ctrl+d` *inside* the `ipython` session, so that I can `join()` my threads. – Pablo Nov 21 '16 at 22:16

1 Answers1

0

I found the (possible) answer here: How can I capture 'Ctrl-D' in python interactive console?

I don't know if it's different with iPython, but Ctrl-D should raise an EOFError. Try this code:

try:
    raw_input()
except EOFError:
    pass

If this does not work with iPython, please tell me.

Community
  • 1
  • 1
Douglas
  • 1,304
  • 10
  • 26