我有一个 Python 网络流量可视化工具。它使用 Twisted 进行网络连接并调用 run()
它还有 matplotlib 用于绘图并调用 show()
。这两个函数似乎都没有返回,但我需要调用它们来启动网络,然后显示绘图并最终在网络上发生事情时更新绘图。有什么解决办法吗?我需要线程吗?
最佳答案
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
导入到顶部) - 在导入
pyplot
之前,我强制 matplotlib 通过use('GTK')
调用使用 Gtk - 在导入
reactor
之前,我强制 Twisted 通过gtk2reactor.install()
调用使用 Gtk - 我用
mainloop
方法调用我自己的Show
子类替换了对pyplot.show()
的调用,启动了 Gtk 主循环和 Twisted 主循环(均通过reactor.run()
)
这个例子似乎运行得相当好。我还没有对此进行太多探索,因此如果存在仅在更高级的用法下出现的问题,我不知道。
关于python - 如何运行两个Python阻塞函数matplotlib.show()和twisted.reactor.run()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10391123/