gpt4 book ai didi

python - 线程忽略 KeyboardInterrupt 异常

转载 作者:IT老高 更新时间:2023-10-28 20:37:57 30 4
gpt4 key购买 nike

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

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 block ,所以KeyboardInterrupt 没有被捕获。我的第一个想法是使用 thread.join,但这似乎会阻塞主进程(忽略 KeyboardInterrupt),直到 thread 完成。

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

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

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com