我正在运行以下简单代码:
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。为什么?此代码有什么问题?
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完成。
time.sleep
try...except
KeyboardInterrupt
thread.join
thread
thread.daemon=True 导致线程在主进程结束时终止。
thread.daemon=True