如何正确设置 sys.excepthook

我编写了以下代码来理解多进程环境中的 sys.excepthook。我正在使用 python 3。我创建了 2 个进程,它们将打印并等待获取 ctrl+c。


from multiprocessing import Process

import multiprocessing

import sys

from time import sleep



class foo:

    def f(self, name):

        try:

            raise ValueError("test value error")

        except ValueError as e:

            print(e)

        print('hello', name)

        while True:

            pass



def myexcepthook(exctype, value, traceback):

    print("Value: {}".format(value))

    for p in multiprocessing.active_children():

        p.terminate()



def main(name):

    a = foo()

    a.f(name)


sys.excepthook = myexcepthook

if __name__ == '__main__':

    for i in range(2):

        p = Process(target=main, args=('bob', ))

        p.start()

当我按下时,我期待以下结果ctrl+C


python /home/test/test.py

test value error

hello bob

test value error

hello bob


Value: <KeyboardInterrupt>

但不幸的是,我得到了以下结果。


/home/test/venvPython3/bin/python /home/test/test.py

test value error

hello bob

test value error

hello bob

Error in atexit._run_exitfuncs:

Traceback (most recent call last):

Process Process-1:

  File "/usr/lib/python3.6/multiprocessing/popen_fork.py", line 28, in poll

    pid, sts = os.waitpid(self.pid, flag)

KeyboardInterrupt

Traceback (most recent call last):

  File "/usr/lib/python3.6/multiprocessing/process.py", line 258, in _bootstrap

    self.run()

  File "/usr/lib/python3.6/multiprocessing/process.py", line 93, in run

    self._target(*self._args, **self._kwargs)

  File "/home/test/test.py", line 26, in main

    a.f(name)

  File "/home/test/test.py", line 15, in f

    pass

KeyboardInterrupt

Process Process-2:

Traceback (most recent call last):

  File "/usr/lib/python3.6/multiprocessing/process.py", line 258, in _bootstrap

    self.run()

  File "/usr/lib/python3.6/multiprocessing/process.py", line 93, in run

    self._target(*self._args, **self._kwargs)

  File "/home/test/test.py", line 26, in main

    a.f(name)

  File "/home/test/test.py", line 15, in f

    pass

KeyboardInterrupt


Process finished with exit code 0

如果有人能指出我做错了什么,那将是一个很大的帮助。另外,请让我知道如何获得预期的输出。


米脂
浏览 90回答 1
1回答

蝴蝶不菲

你几乎做到了。首先,使用exctype打印:def myexcepthook(exctype, value, traceback):&nbsp; &nbsp; print("Value: {}".format(exctype))&nbsp; &nbsp; for p in multiprocessing.active_children():&nbsp; &nbsp; &nbsp; &nbsp; p.terminate()并join()创建流程,防止过早退出if __name__ == '__main__':&nbsp; &nbsp; pr = []&nbsp; &nbsp; for i in range(2):&nbsp; &nbsp; &nbsp; &nbsp; p = Process(target=main, args=('bob', ))&nbsp; &nbsp; &nbsp; &nbsp; p.start()&nbsp; &nbsp; &nbsp; &nbsp; pr.append(p)&nbsp; &nbsp; for p in pr:&nbsp; &nbsp; &nbsp; &nbsp; p.join()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python