- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
根据the official python documentation ,“finally”语句总是会被执行,因此通常用于清理操作。
If "finally" is present, it specifies a ‘cleanup’ handler. The "try" clause is executed, including any "except" and "else" clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The "finally" clause is executed. If there is a saved exception, it is re-raised at the end of the "finally" clause. If the "finally" clause raises another exception or executes a return or break statement, the saved exception is discarded:
但是,当我在线程中实现“try-finally”语句时,“finally”部分似乎没有被执行。
from __future__ import print_function
import threading
def thread1():
try:
while True:
pass
except:
print("exception")
finally:
print("closed")
t = threading.Thread(target = thread1)
t.setDaemon(True)
t.start()
while True:
pass
当被 ctrl-c 中断时,“close”不会打印在屏幕上。这是为什么?
虽然在下面的代码中“最终”确实有效(毫不奇怪)
from __future__ import print_function
try:
while True:
pass
finally:
print("closed")
最佳答案
在 the documentation对于 thread
模块(它是 threading
的基础):
When the main thread exits, it is system defined whether the other threads survive. On SGI IRIX using the native thread implementation, they survive. On most other systems, they are killed without executing
try ... finally
clauses or executing object destructors.
关于python - finally 语句在线程中不生效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42291212/
我是一名优秀的程序员,十分优秀!