【问题标题】:Handling Exception in multiprocess处理多进程中的异常
【发布时间】:2015-09-09 12:00:20
【问题描述】:

我有 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 中引发错误,但这似乎不是很干净。

【问题讨论】:

    标签: python python-2.7 exception-handling multiprocessing


    【解决方案1】:

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

    【讨论】:

    • 在不创建RemoteException 的情况下也应该可以工作,不是吗?我可以简单地发送e 并使用您的if isinstance(e,Exception):A 中引发异常。我明天试试。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-23
    • 2016-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    相关资源
    最近更新 更多