小编典典

线程忽略KeyboardInterrupt异常

python

我正在运行以下简单代码:

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。为什么?此代码有什么问题?


阅读 354

收藏
2020-12-20

共1个答案

小编典典

尝试

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...except过早地跳出该块,因此KeyboardInterrupt不会被捕获。我的第一个想法是使用thread.join,但这似乎阻塞了主进程(忽略KeyboardInterrupt),直到thread完成。

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

2020-12-20