threading ignores KeyboardInterrupt exception(线程忽略 KeyboardInterrupt 异常)
问题描述
我正在运行这个简单的代码:
I'm running this simple code:
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('
! Received keyboard interrupt, quitting threads.
')
但是当我运行它时,它会打印出来
But when I run it, it prints
$ python prova.py
.
.
^C.
.
.
.
.
.
.
.
Exception KeyboardInterrupt in <module 'threading' from '/usr/lib/python2.6/threading.pyc'> ignored
事实上,python 线程忽略了我的 Ctrl+C 键盘中断并且不打印 Received Keyboard Interrupt
.为什么?这段代码有什么问题?
In fact python thread ignore my Ctrl+C keyboard interrupt and doesn't print Received Keyboard Interrupt
. Why? What is wrong with this code?
推荐答案
试试
try:
thread=reqthread()
thread.daemon=True
thread.start()
while True: time.sleep(100)
except (KeyboardInterrupt, SystemExit):
print '
! Received keyboard interrupt, quitting threads.
'
没有调用time.sleep
,主进程太早跳出try...except
块,所以KeyboardInterrupt
没有被捕获.我的第一个想法是使用 thread.join
,但这似乎会阻塞主进程(忽略 KeyboardInterrupt),直到 thread
完成.
Without the call to time.sleep
, the main process is jumping out of the try...except
block too early, so the KeyboardInterrupt
is not caught. My first thought was to use thread.join
, but that seems to block the main process (ignoring KeyboardInterrupt) until the thread
is finished.
thread.daemon=True
导致线程在主进程结束时终止.
thread.daemon=True
causes the thread to terminate when the main process ends.
这篇关于线程忽略 KeyboardInterrupt 异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:线程忽略 KeyboardInterrupt 异常


基础教程推荐
- 筛选NumPy数组 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01