编程语言
首页 > 编程语言> > python – 线程忽略KeyboardInterrupt异常

python – 线程忽略KeyboardInterrupt异常

作者:互联网

我正在运行这个简单的代码:

import threading, time

class reqthread(threading.Thread):    
    def run(self):
        for i in range(0, 10):
            time.sleep(1)
            print('.')

try:
    thread = reqthread()
    thread.start()
except (KeyboardInterrupt, SystemExit):
    print('\n! Received keyboard interrupt, quitting threads.\n')

但是当我运行它时,它会打印出来

$python prova.py
.
.
^C.
.
.
.
.
.
.
.
Exception KeyboardInterrupt in <module 'threading' from '/usr/lib/python2.6/threading.pyc'> ignored

实际上python线程忽略我的Ctrl C键盘中断并且不打印Received Keyboard Interrupt.为什么?这段代码有什么问题?

解决方法:

尝试

try:
  thread=reqthread()
  thread.daemon=True
  thread.start()
  while True: time.sleep(100)
except (KeyboardInterrupt, SystemExit):
  print '\n! Received keyboard interrupt, quitting threads.\n'

如果没有调用time.sleep,主进程就会跳过try …除了块太早,所以没有捕获到KeyboardInterrupt.我的第一个想法是使用thread.join,但这似乎阻止了主进程(忽略KeyboardInterrupt),直到线程完成.

thread.daemon = True会导致线程在主进程结束时终止.

标签:python,multithreading,events,exception,keyboardinterrupt
来源: https://codeday.me/bug/20190918/1810796.html