title: IPython: executing a function after ctrl+d keypress
body: <p>I have right now a <code>django</code> project and I like to test and check things by executing <code>./manage.py shell</code> which spawns an <code>ipython</code> shell.</p>
  
  <p>In some projects I have a threads that run in the background and do stuff. Sometimes, while in a <code>ipython</code> session, I need to start one of these threads. I usually forget to <code>join()</code> the thread <strong>before</strong> I press <code>ctrl+d</code> to exit the shell, at which point <code>ipython</code> blocks.</p>
  
  <p>I tried registering a cleanup method with <code>atexit.register</code> but that didn't work because it is called too late.</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>I put that in a file <code>test.py</code></p>
  
  <pre><code>$ ipython
  In [1]: %run "test.py"
  
  In [2]: ctrl+d pressed                                                                                                                                                      
  ATEXIT: stop
  </code></pre>
  
  <p>As you can see the function registered with <code>atexit</code> was executed. However, if I start the thread:</p>
  
  <pre><code>$ 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
  </code></pre>
  
  <p>So, what I need is a way of executing <code>stop()</code> after I press <code>ctrl+d</code>. I've found this thread <a href="https://stackoverflow.com/questions/39499748/override-ipython-exit-function-or-add-hooks-in-to-it#39499913">Override ipython exit function - or add hooks in to it</a> 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 <code>ctrl+d</code>?</p>