Python 从主进程和派生进程使用matplotlib

Python 从主进程和派生进程使用matplotlib,python,matplotlib,multiprocessing,xcb,Python,Matplotlib,Multiprocessing,Xcb,有没有一种方法可以从主函数和派生的进程中使用matplotlib 在我当前的应用程序中,我希望绘制模拟的中间结果,并通过使用多处理模块生成子流程来实现,以允许模拟在后台进行,并允许用户选择关闭或保持绘图打开。在某一点上,用户可以修改继续模拟,因此主功能将绘制到目前为止的结果,并等待用户响应。但是,执行此操作时,程序会显示错误消息: [xcb] Unknown sequence number while processing queue [xcb] Most likely this is a mu

有没有一种方法可以从主函数和派生的进程中使用
matplotlib

在我当前的应用程序中,我希望绘制模拟的中间结果,并通过使用
多处理
模块生成子流程来实现,以允许模拟在后台进行,并允许用户选择关闭或保持绘图打开。在某一点上,用户可以修改继续模拟,因此主功能将绘制到目前为止的结果,并等待用户响应。但是,执行此操作时,程序会显示错误消息:

[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归档文件后,我发现有一篇文章报告了同样的内容,评论说“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()
当包含
导入matplotlib.pyplot作为plt时
代码运行良好,这有点奇怪,因为我觉得在这种情况下,
plt
而不是
matplotlib.pyplot
应该可以访问。

生成类似于那里的代码:。请确保使用mp.set_start_方法(“spawn”)生成它,并在已跨越的函数中包含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()