Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在派生进程中处理异常_Python_Multiprocessing - Fatal编程技术网

Python 在派生进程中处理异常

Python 在派生进程中处理异常,python,multiprocessing,Python,Multiprocessing,我想写一个进程来执行来自另一个进程的命令。这涉及到接收命令、处理命令并用结果回复调用进程。在请求执行下一个命令之前,调用进程应等待应答。这就是我到目前为止的想法: import multiprocessing import time class CommandProcessor(multiprocessing.Process): def __init__(self): multiprocessing.Process.__init__(self) self

我想写一个进程来执行来自另一个进程的命令。这涉及到接收命令、处理命令并用结果回复调用进程。在请求执行下一个命令之前,调用进程应等待应答。这就是我到目前为止的想法:

import multiprocessing
import time

class CommandProcessor(multiprocessing.Process):
    def __init__(self):
        multiprocessing.Process.__init__(self)
        self.command = multiprocessing.Queue()
        self.result = multiprocessing.Queue()

    def run(self):
        while True:
            c = self.command.get()
            if not c: break 
            self.result.put(str(c)) 

    def execute(self, n):
        self.command.put(n)
        return self.result.get()

    def stop(self):
        self.command.put(None)
        self.join()

try:
    p = CommandProcessor()
    p.start()
    r = p.execute(1)
    print("Result: "+r)
    r = p.execute(2)
    print("Result: "+r)
    r = p.execute(3)
    print("Result: "+r)
finally:
    p.stop()

我的设计至少有一个问题。例如,如果
CommandProcessor
中出现异常,主进程将无限期地等待
返回self.result.get()
。我可以给
get()
方法添加一个超时,但是我运行的一些命令需要相对较长的时间来执行。因此,超时时间必须足够长,才能保证它们的执行。如果出现异常,并且有用的堆栈跟踪转储到标准输出,如何处理该异常,以使两个进程都终止。

将其包装在
try/except
中:

示例:(除外)

它是在生成的进程中执行的
run()
方法,因此您需要在这里执行异常处理。下面是一个示例,返回堆栈跟踪作为结果。另外,请注意检测
None
命令(即“停止”信号)的正确方法

您得到的结果是1和3工作正常,但有2个错误:

Result: 1
Result: Traceback (most recent call last):
  File "a.py", line 17, in run
    1/(c-2)  # Throws exception if c is 2.
ZeroDivisionError: integer division or modulo by zero

Result: 3

因此,将它包装在一个
try/except
中,并做一些合理的事情。这没有帮助,因为这个方法是从主进程调用的,我指的是CommandProcessor进程中的异常。
import traceback

class CommandProcessor():
    ...

    def run(self):
        while True:
            c = self.command.get()
            if c is None:
                break
            try:
                1/(c-2)  # Throws exception if c is 2.
            except:
                c = traceback.format_exc()
            self.result.put(str(c)) 
Result: 1
Result: Traceback (most recent call last):
  File "a.py", line 17, in run
    1/(c-2)  # Throws exception if c is 2.
ZeroDivisionError: integer division or modulo by zero

Result: 3