Python 多进程中的异常处理

Python 多进程中的异常处理,python,python-2.7,exception-handling,multiprocessing,Python,Python 2.7,Exception Handling,Multiprocessing,我有两个进程A和B,通过多处理.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() exce

我有两个进程
A
B
,通过
多处理.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
上不会发生任何事情。我想知道是否有一种python方法可以将异常传输到
a
,或者我应该通过
管道发送一些虚拟消息,或者杀死管道以在
a
中引发错误,但这似乎不是很干净。

好吧,您需要通过管道发送自己的消息。好像是你 要将异常从
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

当然,
A
B
进程应该共享相同的
RemoteException
类。

也应该在不创建
RemoteException
的情况下工作,不是吗?我可以简单地发送
e
并使用您的
if isinstance(e,Exception):
A
中引发异常。我明天就试试。谢谢你的帮助!