Hi all,
I found the recent ginput function by Gael is really cool.
On the other hand, I often need to take an input from other sources
(I mean, other than matplotlib itself, e.g., raw_input).
I don't think running a blocking function, such as a raw_input,
without freezing the figure canvas
has been easy in matplotlib (especially when you're in an interactive mode).
But with ginput in place now, it seems quite easy.
So, I'm attaching my simple implementation of ginput-like function for
an arbitrary blocking function.
The code is largely based on the current ginput implementation.
You can use it as
>>> from PylabBlockingInput import BlockingInput
>>> readinput = BlockingInput(raw_input)
>>> r = readinput()
The blocking function itself is run in a separate thread while the
main thread updates the
figure with flush_events calls. Here are a few things
* I only tested this with GtkAgg backend.
* I must admit that I have very little experience with thread
programming, and I'm not sure how usable (or safe) this approach
will be in general.
* Since the blocking function is not attached to any particular
figure, gcf().canvas.flush_events is
run by default.
I hope this is useful to others
and any comments will be welcomed.
Cheers,
-JJ
ps. I believe this is my first post in matplotlib-devel list. Thanks a
lot to John and others for a great plotting package.
import time
import threading
class BlockingInputHelperThread(threading.Thread):
""" A helper thread inside which the blocking function will be run.
"""
def __init__(self, blocking_function):
self.blocking_function = blocking_function
threading.Thread.__init__(self)
self.exception = None
def run(self):
try:
self.returnvalue = self.blocking_function()
except Exception, e:
self.exception = e
class BlockingInput(object):
""" Class that creates a callable object to run a blocking function
(in a seperate thread) without freezing the figure.
"""
def __init__(self, blocking_func, fig=None):
if fig is None:
from pylab import gcf
self.fig = gcf()
else:
self.fig = fig
self.blocking_func = blocking_func
def __call__(self):
""" Run the blocking function in a seperate thread while the main
thread updates the figure. Returns the return value of
the original blocking function. Any exception from the original
blocking function will be also raised.
"""
# Ensure that the figure is shown
self.fig.show()
thr = BlockingInputHelperThread(self.blocking_func)
thr.start()
while thr.isAlive():
self.fig.canvas.flush_events()
time.sleep(0.01)
if thr.exception:
raise thr.exception
else:
return thr.returnvalue
-------------------------------------------------------------------------
This SF.net email is sponsored by: Microsoft
Defy all challenges. Microsoft(R) Visual Studio 2008.
http://clk.atdmt.com/MRT/go/vse0120000070mrt/direct/01/
_______________________________________________
Matplotlib-devel mailing list
Matplotlib-devel@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-devel