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

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...except块,因此没有捕获KeyboardInterrupt。我的第一个想法是使用thread.join,但这似乎阻塞了主进程(忽略KeyboardInterrupt),直到thread完成为止。
thread.daemon=True导致线程在主进程结束时终止。

关于python - 线程忽略KeyboardInterrupt异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3788208/

10-09 22:02