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
中引发异常。我明天就试试。谢谢你的帮助!