如何防止在设置信号处理程序时忽略异常:<module'threading'=“”from =“”... =“”> </module>

时间:2014-06-11 18:20:18

标签: python multithreading python-3.x exception-handling signals

拥有此代码:

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)

修改 尝试在t.join()中的最后一个t.join(1)循环中添加for(或main}后,我得到了同样的内容,但我必须按 Ctrl < kbd> c 得到此错误并退出程序。

1 个答案:

答案 0 :(得分:5)

问题在于您没有set your threads to be daemons并且没有加入线程,因此当主线程死亡时,其余线程将继续在后台运行。

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

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()