在多进程中处理异常

Handling Exception in multiprocess

我有 2 个进程 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 发送一些虚拟消息,或者终止管道以在 A 中引发错误,但是看起来不太干净。

据我所知,您需要通过管道发送您自己的消息。好像你 想要将异常从 B 发送到 AB中的异常代码 处理可能是这样的:

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 class.