Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:生成安全的临时文件名_Python_Unit Testing_Standard Library_Temporary Files - Fatal编程技术网

Python:生成安全的临时文件名

Python:生成安全的临时文件名,python,unit-testing,standard-library,temporary-files,Python,Unit Testing,Standard Library,Temporary Files,在为后端类编写单元测试的上下文中,我需要一种安全的方法来生成临时文件名。我目前的做法是: fp = tempfile.NamedTemporaryFile(delete=False) fp.close() with Backend(fp.name) as backend: ...run the test... os.unlink(fp.name) 这有点尴尬。是否存在标准库上下文管理器,允许通过以下方式实现相同的功能: with TempFileName() as name:

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

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 ...
因此,我们必须创建一个文件,而不仅仅是一个文件名。我同意。这正是我的代码所做的。我正在寻找一个上下文管理器,它可以更好地打包。