且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用多重处理时,Python rpy2和matplotlib冲突

更新时间:2022-06-19 01:37:25

在Mac OS X上,当您在主线程之外执行GUI操作时会发生此错误,这正是您将绘图函数移至多处理过程中所要执行的操作.Pool(我想出于同样的原因,它也不会在Windows上运行-因为Windows具有相同的要求).我可以想象它工作的唯一方法是使用池生成数据,然后让您的主线程在循环中等待返回的数据(队列是我通常处理它的方式...).

This error occurs on Mac OS X when you perform a GUI operation outside the main thread, which is exactly what you are doing by shifting your plot function to the multiprocessing.Pool (I imagine that it will not work on Windows either for the same reason - since Windows has the same requirement). The only way that I can imagine it working is using the pool to generate the data, then have your main thread wait in a loop for the data that's returned (a queue is the way I usually handle it...).

这里是一个示例(认识到这可能无法实现您想要的功能-同时"绘制所有图形吗?-plt.show()块,因此一次只能绘制一个,我注意到您没有它在您的示例代码中-但是在屏幕上我什么都看不到-但是,如果我将其取出-没有阻塞,也没有错误,因为所有GUI功能都在主线程中发生)

Here is an example (recognizing that this may not do what you want - plot all the figures "simultaneously"? - plt.show() blocks so only one is drawn at a time and I note that you do not have it in your sample code - but without I don't see anything on my screen - however, if I take it out - there is no blocking and no error because all GUI functions are happening in the main thread):

import multiprocessing
import matplotlib.pyplot as plt
import numpy as np
import rpy2.robjects as robjects

data_queue = multiprocessing.Queue()


def main():
    pool = multiprocessing.Pool()
    num_figs = 10

    # generate some random numbers
    input = zip(np.random.randint(10,10000,num_figs), range(num_figs))  
    pool.map(worker, input)

    figs_complete = 0
    while figs_complete < num_figs:
        data = data_queue.get()
        plt.figure()
        plt.plot(data)
        plt.show()
        figs_complete += 1

def worker(args):
    num, i = args
    data = np.random.randn(num).cumsum()
    data_queue.put(data)
    print('done ',i)

main()

希望这会有所帮助.