如何防止在以下情况中忽略异常:<模块'threading'from ...>同时设置信号处理程序? [英] How to prevent Exception ignored in: <module 'threading' from ... > while setting signal handler?

查看:121
本文介绍了如何防止在以下情况中忽略异常:<模块'threading'from ...>同时设置信号处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有此代码:

def signal_handler(signal, frame):
    print("exiting")
    sys.exit(0)

if __name__ == "__main__":
    signal.signal(signal.SIGINT, signal_handler)

    threads_arr = []
    for i in list:
        t = threading.Thread(target=myFunc, args=(i))
        threads_arr.append(t)
        t.start()

如何防止在按 Ctrl + C

Exception ignored in: <module 'threading' from '/usr/lib/python3.4/threading.py'>
Traceback (most recent call last):
  File "/usr/lib/python3.4/threading.py", line 1294, in _shutdown
    t.join()
  File "/usr/lib/python3.4/threading.py", line 1060, in join
    self._wait_for_tstate_lock()
  File "/usr/lib/python3.4/threading.py", line 1076, in _wait_for_tstate_lock
    elif lock.acquire(block, timeout):
  File "./script.py", line 28, in signal_handler
    sys.exit(0)
SystemExit: 0

第28行指向的是 sys.exit(0)?

编辑尝试在 main <的最后一个 for 循环中添加 t.join()(或 t.join(1))之后/code>我得到了相同的结果,尽管我必须按 Ctrl + C 来获取此错误并退出程序.

EDIT After trying to add t.join() (or t.join(1)) in the last for loop in main I get the same although I have to press Ctrl+C to get this error and exit the program.

推荐答案

问题是您没有将您的线程设置为守护程序,并且您没有加入线程,因此当主线程死亡时,其余线程将继续在后台运行.

The problem is that you didn't set your threads to be daemons and you didn't join the threads, so when the main thread dies the rest keep running in the background.

如果您将代码编辑如下,那么它将起作用:

If you edit your code to be as follows then it will work:

import signal
import threading
import sys

def signal_handler(signal, frame):
    print("exiting")
    sys.exit(0)

if __name__ == "__main__":
    signal.signal(signal.SIGINT, signal_handler)

    threads_arr = []
    for i in list:
        t = threading.Thread(target=myFunc, args=(i))
        threads_arr.append(t)
        t.daemon = True # die when the main thread dies
        t.start()
    for thr in threads_arr: # let them all start before joining
        thr.join()

这篇关于如何防止在以下情况中忽略异常:&lt;模块'threading'from ...&gt;同时设置信号处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆