This Page

Quick search

# Demo of using multiprocessing for generating data in one process and plotting# in another.# Written by Robert Cimrman# Requires >= Python 2.6 for the multiprocessing module or having the# standalone processing module installedfrom__future__importprint_functionimporttimetry:frommultiprocessingimportProcess,PipeexceptImportError:fromprocessingimportProcess,Pipeimportnumpyasnpimportmatplotlibmatplotlib.use('GtkAgg')importmatplotlib.pyplotaspltimportgobjectclassProcessPlotter(object):def__init__(self):self.x=[]self.y=[]defterminate(self):plt.close('all')defpoll_draw(self):defcall_back():while1:ifnotself.pipe.poll():breakcommand=self.pipe.recv()ifcommandisNone:self.terminate()returnFalseelse:self.x.append(command[0])self.y.append(command[1])self.ax.plot(self.x,self.y,'ro')self.fig.canvas.draw()returnTruereturncall_backdef__call__(self,pipe):print('starting plotter...')self.pipe=pipeself.fig,self.ax=plt.subplots()self.gid=gobject.timeout_add(1000,self.poll_draw())print('...done')plt.show()classNBPlot(object):def__init__(self):self.plot_pipe,plotter_pipe=Pipe()self.plotter=ProcessPlotter()self.plot_process=Process(target=self.plotter,args=(plotter_pipe,))self.plot_process.daemon=Trueself.plot_process.start()defplot(self,finished=False):send=self.plot_pipe.sendiffinished:send(None)else:data=np.random.random(2)send(data)defmain():pl=NBPlot()foriiinrange(10):pl.plot()time.sleep(0.5)raw_input('press Enter...')pl.plot(finished=True)if__name__=='__main__':main()