使用来自main和衍生过程的matplotlib

问题描述 投票:3回答:1

有没有办法从主函数和衍生过程中使用matplotlib

在我当前的应用程序中,我希望绘制模拟的中间结果,并通过使用multiprocessing模块生成子流程来实现,以允许模拟在后台进行,并且用户可以选择关闭或保持绘图打开。在某一点上,用户可以修改连续模拟,因此主函数到目前为止绘制结果并等待用户响应。但是,这样做会导致程序崩溃并显示错误消息:

[xcb] Unknown sequence number while processing queue
[xcb] Most likely this is a multi-threaded client and XInitThreads has not been called
[xcb] Aborting, sorry about that.
python: xcb_io.c:274: poll_for_event: Assertion `!xcb_xlib_threads_sequence_lost' failed.
Aborted

如果我删除子流程中的中间步骤绘图或跳过主函数中的绘图,程序运行正常。

现在我通过产生另一个子流程来绘制和检索用户输入(使用multiprocessing.Queue()join()方法)来规避问题。然而,这似乎有点超级必须这样做,因此如果有更好的方法,我真的很感激。

查看stackoverflow存档我发现在同一个error上报告的帖子是评论“matplotlib在多处理方面效果不佳”。但没有提出解决方案/解决方法。

以下代码重现了该问题:

#! /usr/bin/env python


import matplotlib, multiprocessing

matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

def plot(): 
   fig = matplotlib.pyplot.figure()
   fig.show()    

plot()
p = multiprocessing.Process(target=plot, args=())
p.start() 
raw_input()

作为旁注,我发现只需使用import matplotlib fig = matplotlib.pyplot.figure()上的代码扼流圈,同时包括import matplotlib.pyplot as plt,代码运行良好,这有点奇怪,因为我的印象是在这种情况下plt但不是matplotlib.pyplot应该是可访问的。

python matplotlib multiprocessing xcb
1个回答
0
投票

产卵类似于那里:How to start 2x Matplotlib interactiv windows, viewer of another main window?。确保使用mp.set_start_method('spawn')生成它并在spanned函数中包含matplotlib。类似于下面的代码(未经测试)

import matplotlib, multiprocessing

matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

def plot(): 
   import matplotlib
   fig = matplotlib.pyplot.figure()
   fig.show()    

plot()
multiprocessing.set_start_method('spawn') 
p = multiprocessing.Process(target=plot, args=())
p.start() 
raw_input()
© www.soinside.com 2019 - 2024. All rights reserved.