有人能解释一下interrupt_main()方法是如何在Python中工作的吗?
我有一段Python代码:
import time, thread
def f():
time.sleep(5)
thread.interrupt_main()
def g():
thread.start_new_thread(f, ())
time.sleep(10)
print time.time()
try:
g()
except KeyboardInterrupt:
print time.time()当我尝试运行它时,它给出了以下输出:
1380542215.5
# ... 10 seconds break...
1380542225.51但是,如果我手动中断程序(CTRL),线程将被正确地中断:
1380542357.58
^C1380542361.49为什么在第一个示例中线程中断只发生在10秒(而不是5秒)之后?
我找到了一个古代线程n Python邮件列表,但它几乎什么也解释不了。
发布于 2013-09-30 15:40:39
raise KeyboardInterrupt不中断time.sleep()。前者完全在python解释器中处理,后者调用操作系统函数。
因此,在您的情况下,键盘中断是处理的,但只有当time.sleep()完成其系统调用。
试一试:
def g():
thread.start_new_thread(f, ())
for _ in range(10):
time.sleep(1)https://stackoverflow.com/questions/19093899
复制相似问题