raw_input in matplotlib with plot interaction

This page was originally published on blog.procrastination.nl, which is still on-line for archival purposes.

When working with data, you sometimes need to view the data and give input on how to continue. However, a simple
answer = raw_input()
will not work: the plot GUI will block while the raw_input() is waiting. The following is a (admittedly hacky) solution to this problem: run raw_input() in a seperate thread, and poll the GUI using waitforbuttonpress():
import threading
import matplotlib
from __builtin__ import raw_input as original_raw_input

def raw_input(*args, **kwargs):
    value = []
    ri = lambda: value.append(original_raw_input(*args, **kwargs))
    t = threading.Thread(target=ri)
    while t.isAlive():
        if matplotlib._pylab_helpers.Gcf.get_all_fig_managers():
    return value[0]
raw_input.__doc__ = original_raw_input.__doc__

if __name__=="__main__":
    print raw_input("...> ")
When a value is entered, the program might wait (for up to 0.1s), which is a fairly minor issue. There's probably also a way to deadlock it - but hey, a data analysis script is not production code ;-)