gpt4 book ai didi

python - finally 语句在线程中不生效

转载 作者:行者123 更新时间:2023-12-02 02:06:28 24 4
gpt4 key购买 nike

根据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/

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