如何在多处理中捕获工作进程中的异常

2024-05-17 02:53:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python(2.7.3)中的多处理模块,希望调试我的工作人员中正在进行的一些工作。但是,我似乎无法捕获工作线程中的任何异常。

一个简单的例子:

import multiprocessing as mp


a=[1]
def worker():
    print a[2]


def pool():
    pool = mp.Pool(processes=1)
    pool.apply_async(worker, args = ())
    pool.close()
    pool.join()
    print "Multiprocessing done!"


if __name__ == '__main__':
    pool()

这将引发索引器错误,但我的输出只是

    Multiprocessing done!

有没有一种方法可以显示工作线程中发生的所有异常,而无需手动引发我自己的异常?


Tags: 模块importdefasmp线程multiprocessing例子
2条回答

除非调用^{}^{} method(返回值apply_async),否则不会引发错误:

根据^{} documentation

Return the result when it arrives. If timeout is not None and the result does not arrive within timeout seconds then multiprocessing.TimeoutError is raised. If the remote call raised an exception then that exception will be reraised by get().

def pool():
    pool = mp.Pool(processes=1)
    result = pool.apply_async(worker, args=())
    result.get() # <------------
    pool.close()
    pool.join()
    print "Multiprocessing done!"

我想福斯特鲁给了你你所需要的。我只想再扩大一点。

如果您不仅要获得错误,而且要获得原始上下文(即,要知道异常发生在worker()的第1行),那么您可以检查this nice post by Ned Batchelder,它解释了如何使用原始上下文重新访问异常。

这对议员来说不管用,所以只是为了你需要更多的东西。This SO Question使用更显式的多处理技术而不是mp.Pool来覆盖您的问题。

相关问题 更多 >