gpt4 book ai didi

python - 如何在不关闭资源的情况下留下 `with` block ?

转载 作者:行者123 更新时间:2023-12-05 00:52:58 24 4
gpt4 key购买 nike

我正在尝试实现类似于

from tempfile import TemporaryFile

def open_head(file_path):
with open(file_path, 'r') as f,
TemporaryFile() as tf:
for i in range(0,10):
tf.write(f.read_line())
return tf

使得调用者获得临时文件的所有权。

特别是,我不希望 with 语句关闭 TemporaryFile。但是如果在 return 之前出现任何问题,我仍然希望 TemporaryFilewith 语句关闭。

理想情况下,我想把调用者写成

with open_head(file_path):
# more code here

这有可能吗?例如。通过编写 return do_not_close(tf) 或其他一些实用程序功能?

或者我是否完全错误地处理了这个问题,并且有一种更 Pythonic 的方式可以在函数之间返回 TemporaryFiles 或其他资源,同时保证异常安全?

最佳答案

你没有。 open_head 应该采用一个已经打开的句柄,调用者负责关闭它。

from tempfile import TemporaryFile
from itertools import islice


def head(file_path, fh):
with open(file_path) as f:
for line in islice(f, 10):
fh.write(line)


with TemporaryFile() as tf:
head(file_path, tf)
# Do other stuff with tf before it gets closed.

一般来说,每当你在函数中打开文件时,问问自己是否可以将实际打开推送给调用者并接受类似文件的对象。除了使您的代码更可重用之外,它还使您的代码更易于测试。 head 不必用实际文件调用:它可以用任何类似文件的对象调用,例如 io.StringIO


换一种说法:with 语句强制执行通知

If you open the file, you are responsible for closing it as well.

contrapositive该建议是

If you aren't responsible for closing the file, you aren't responsible for opening the file, either.

关于python - 如何在不关闭资源的情况下留下 `with` block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68702826/

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