ipython -pylab trick

I had a problem yesterday running a script in interactive mode in
ipython -pylab using the gtk backend. In the script there was some
expensive computation, and I wanted to break out of it by hitting
CTRL-C. Because of the nastiness of signal handling across threads,
this isn't possible, though Fernando tells me it is keeping him up
nights. ipython prints a message that it got a CTRL-C, but can't
cause the code running in the gui thread to exit cleanly.

One hack/workaround solution is to check for the IPython.Shell state
variable at various points in your code

  # some script you want to run from ipython -pylab or ipython -gthread
  # with "run"
  import IPython.Shell
  from pylab import figure, show, setp

  def ipbreak():
      if IPython.Shell.KBINT:
          IPython.Shell.KBINT = False
          raise SystemExit

  for i in somerange:


Then if you want to interrupt the script, you can with CTRL-C. Of
course the trick is to remember to sprinkle these throughout your code
ahead of time. The script will run normally outside of ipython, and
as long as the function call and boolean check are cheap compared to
your expensive function, shouldn't hurt performance.

Thanks Fernando for the suggestion!