主线程未捕获KeyboardInterrupt

时间:2017-08-04 16:51:52

标签: python multithreading

我在这里看到了几个关于以干净的方式杀死python线程的线程,但我认为我有一个更基本的问题。假设我有一些看起来像这样的代码:

t1 = threading.Thread(target=method1, args=(args1,))
t1.daemon = True

t2 = threading.Thread(target=method2, args=(args2, ))
t2.daemon = True
t1.start()
t2.start()

while True:
    time.sleep(1)

我希望主线程注意到Ctrl-C键盘中断,并且从那里我可以根据上下文适当地处理其他线程(t1t2)的终止。但无论我做什么,我都无法获得主线程来捕获KeyboardInterrupt。我尝试过这样的事情:

try:
    while True: time.sleep(100)
except KeyboardInterrupt:
    print "Quitting!"

或类似的东西:

threads = []
threads.append(t1)
threads.append(t2)
while len(threads) > 0:
    try:
        threads = [t for t in threads if t is not None and t.isAlive()]
        time.sleep(1)
    except:
        print "Ctrl - C received, kiling"
        for t in threads:
            t.kill_received = True

但是这些都不会在异常处理程序中打印消息,只显示:

    Exception in thread Thread-3:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
    self.run()
  File "/usr/local/lib/python2.7/dist-packages/audioread/gstdec.py", line 149, in run
    self.loop.run()
  File "/usr/lib/python2.7/dist-packages/gi/overrides/GLib.py", line 576, in run
    raise KeyboardInterrupt
KeyboardInterrupt

这里的主要问题是如何安全地杀死t1t2(我最终也必须处理这个问题),但为什么呢?主线程没有在这里捕捉KeyboardInterrupt

编辑:正如我已经编写了这些示例,我已经尝试过在try-except块中暂停while循环的方法。还有其他想法吗?

0 个答案:

没有答案