如何运行两个python阻塞函数matplotlib.show()和twisted.reactor.run()?

时间:2012-04-30 21:57:04

标签: python multithreading matplotlib twisted

我有一个用于Python网络流量的可视化工具。它使用Twisted进行联网并调用run()它还有matplotlib用于绘图和调用show()。这些功能似乎都没有返回,但是我需要调用它们来启动网络,然后显示情节并最终在网络上发生事情时更新情节。有解决方案吗我需要线程吗?

1 个答案:

答案 0 :(得分:3)

matplotlib是一些GUI工具包之上的层。哪个GUI工具包依赖于每个用户的配置,在站点范围的配置上,依赖于matplotlib代码的细节。

Twisted特别支持与某些GUI工具包集成。因此,例如,您可以使用其Gtk后端运行matplotlib并使用Twisted的Gtk集成,然后一切都可以很好地协同工作。

根据我对集成各种主循环的了解,以及对matplotlib源代码的一点点检查,这是一个5分钟的黑客攻击:

if __name__ == '__main__':
    from mpl import main
    raise SystemExit(main())

from matplotlib import use
use('GTK')
from matplotlib import pyplot

from matplotlib.backends import backend_gtk

from twisted.internet import gtk2reactor
gtk2reactor.install()

from twisted.internet import reactor, task

class TwistedGtkShow(backend_gtk.Show):
    running = False
    def mainloop(self):
        if not self.running:
            self.running = True
            reactor.run()

def main():
    pyplot.plot([1,2,3,4])
    pyplot.ylabel('some numbers')

    def proof():
        print 'Twisted!'
    task.LoopingCall(proof).start(3)

    TwistedGtkShow()()

注意:

  • 这是一个名为mpl.py的文件(因此mpl导入顶部)
  • 我强制matplotlib在导入use('GTK')
  • 之前使用Gtk进行pyplot调用
  • 在导入gtk2reactor.install()
  • 之前,我强制Twisted使用Gtk进行reactor调用
  • 我将调用替换为pyplot.show(),调用我自己的Show子类,并使用mainloop方法启动Gtk主循环扭曲的主循环(均为通过reactor.run()

这个例子似乎运作得相当好。我没有对此进行过多的探讨,所以如果有问题只会在更高级的使用下出现,我不知道它们。