为什么在处理来自多进程的异常时.进程键盘中断异常只有在您自己抛出时才能捕获?



假设我有一堆进程,我想运行它们并检查它们是否正常:

procs = [fetcher_process, checker_process, publisher_process, manager_process]
try:
for p in procs:
p.run()
except Exception as e:
print("Oopsie")
exit()
for p in procs:
p.join()

这样的代码可以完美运行,除非您按 Ctrl+C。然后你会在 p.run(( 中得到未处理KeyboardInterrupt,即使它肯定是在 try/exclude 中处理的。

Traceback (most recent call last):
File "/home/keddad/Documents/thevyshka-news-fetcher/main.py", line 39, in <module>
p.run()
File "/usr/lib/python3.8/multiprocessing/process.py", line 108, in run
self._target(*self._args, **self._kwargs)
File "/home/keddad/Documents/thevyshka-news-fetcher/fetchuler.py", line 19, in fetch_news
time.sleep(5)
KeyboardInterrupt

但是,如果我创建自定义 SIGINT 处理程序来抛出相同的KeyboardInterrupt,如下所示:

def raise_keyboards_ex():
raise KeyboardInterrupt()
signal.signal(signal.SIGINT, raise_keyboards_ex)

然后 try/except 开始按预期工作。那么,为什么一个KeyboardInterrupt在这里被抓住而其他的却没有呢?

所以,正如@jasonharper所说,它没有被抓住的原因不是某种魔法——只是因为KeyboardInterrupt不是Exception的子类。它现在抓住它的唯一原因是,我实际上没有上升KeyboardInterrupt而是造成了另一个异常:

try:
for p in procs:
p.run()
except Exception as e:
print("Oopsie")
print(e) # prints "raise_keyboards_ex() takes 0 positional arguments but 2 were given"
exit()

相关内容

  • 没有找到相关文章

最新更新