gpt4 book ai didi

Python:生成安全临时文件名

转载 作者:行者123 更新时间:2023-12-01 04:56:10 25 4
gpt4 key购买 nike

在为后端类编写单元测试的上下文中,我需要一种安全的方法来生成临时文件名。我目前的做法是:

fp = tempfile.NamedTemporaryFile(delete=False)
fp.close()
with Backend(fp.name) as backend:
...run the test...
os.unlink(fp.name)

这有点尴尬。是否存在一个标准库上下文管理器,可以通过以下方式实现相同的目的:

with TempFileName() as name:
with Backend(name) as backend:
...run the test...
<小时/>

当前解决方案

似乎不存在预制上下文管理器。我现在使用的是:

class TemporaryBackend(object):
def __init__(self):
self.fp = tempfile.NamedTemporaryFile(delete=False)
self.fp.close()
self.backend = Backend(self.fp.name)

def __enter__(self):
return self.backend

def __exit__(self, exc_type, exc_value, traceback):
self.backend.close()
os.unlink(self.fp.name)

然后可以与以下内容一起使用:

with TemporaryBackend() as backend:
...run the test...

最佳答案

不要创建临时文件,而是创建一个只有您有权访问的临时目录。一旦完成,您就可以简单地使用任意字符串作为该目录中文件的名称。

d = tempfile.mkdtemp()
tmp_name = "somefile.txt"
with Backend(os.path.join(d, tmp_name)) as backend:
... run test ...
os.remove(tmp_name) # If necessary
os.rmdir(d)

根据您的需要,您可能只需要一个随机字符串:

with Backend(''.join(random.sample(string.lowercase, 8))) as backend:
... run test ...

关于Python:生成安全临时文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27343444/

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