在多进程中处理异常

4

我有两个进程AB,它们通过一个multiprocessing.Pipe()进行通信。当A失败时,我想在B中引发异常。

目前我的代码大致如下:

def A_function():
    try:
        a,b=Pipe()
        B=Process(target=B_function,args=(b,))
        B.start()
        while True:
            a.send(data)
            data_recv=a.recv()
    except Exception as e:
        print e
        #  terminate process properly

def B_function(b):
    try:
        while True:
            data_recv=b.recv()
            # do some work on data_recv, but can fail
            b.send(modified_data)
    except Exception as e:
        print e
        raise # not working on the other process `A`

A=Process(target=A_function)
A.start()

如果进程B失败了,A上就什么都不会发生。我想知道是否有一种Pythonic的方式将异常传递给A,或者我应该通过Pipe发送一些虚假消息,或者杀死Pipe来在A中引发错误,但这似乎不太干净。
1个回答

4
据我所知,您需要通过管道发送自己的消息。看起来您想将异常从B发送到A。在B中处理异常的代码可能如下所示:
class RemoteException(object):
    def __init__(self, exc, err_string, tb):
        self.exception = exc
        self.error_string = err_string
        self.tb = tb

try:
    data_recv = b.recv()
except Exception:
    exception, error_string, tb = sys.exc_info()
    b.send(RemoteException(exception, error_string, tb))
    ...

A中:
while True:
    ..
    data_recv = a.recv()
    if isinstance(data_recv, RemoteException):
        raise data_recv.error_string, None, data_recv.tb

当然,AB两个进程都应该共享同一个RemoteException类,这很重要。

那样也能行,不需要创建 RemoteException 对象吧?我可以直接发送 e 并使用你的 if isinstance(e,Exception): 代码在 A 中抛出异常。明天我会试一下。感谢你的帮助! - CoMartel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接