python - 如何阻止 tempfile.NamedTemporaryFile 在临时文件前缀末尾添加随机字符?

标签 python python-3.x

我正在尝试创建一个临时文件,该文件将在我的程序运行期间持续存在。我希望用户能够在他们选择的文本编辑器中轻松访问该文件。

因此,我想知道如何删除附加到临时文件 NamedTemporaryFile 中前缀末尾的随机字符?因为它会让用户更难输入。

通常是这样的:

aDataSetn6jw9ehy.py

我希望它像这样工作:

aDataSet.py

最佳答案

不幸的是,目前这只能通过跳过障碍来实现。

在内部,tempfile 使用_RandomNameSequence 类,它是一个生成随机名称的迭代器。但是,每个名称的大小被硬编码为八个字符。要支持较短或较长的名称,或具有不同品质的名称,您必须使用自定义名称序列。这个随机名称将被合并到 NamedTemporaryFile 生成的临时文件名中;给出前缀或后缀不会更改此名称,而只是添加到它。

当要求 tempfile.NamedTemporaryFile 生成临时文件名时,它会调用 tempfile._get_candidate_names() 来检索 _RandomNameSequence 迭代器;它只生成该迭代器一次并将其存储在全局变量中。目前,更改迭代器使用的唯一方法是将 tempfile._get_candidate_names() 更改为不同的函数,如下所示:

def gcn():
   # Disable appending a random sequence
   # to the temporary name, or add more
   # characters to that name if necessary
   return iter(["","a","b","c","d","e"])

tempfile._get_candidate_names = gcn

您还可以返回自定义随机名称生成器作为迭代器:

def NameIterator():
   def __iter__(self):
      return self
   def __next__(self):
      # Returns nothing at the moment (indicating
      # to disable appending anything to the temporary
      # name), but this method
      # could also return a randomly generated string
      # instead
      return ""

def gcn():
   return NameIterator()

tempfile._get_candidate_names = gcn

然后,您可以创建一个NamedTemporaryFile,设置临时文件所需的前缀;然后名称的“根”将由新迭代器确定:

f = tempfile.NamedTemporaryFile(prefix="tmp")
print(f.name)  # /tmp/tmp OR /tmp/tmpa OR ...

再说一遍,这一切都是在跳圈,而缺乏自定义随机名称序列的方法似乎显示了 tempfile 模块中的一个缺点;如果这是您关心的事情,请在 bugs.python.org 中打开报告.

关于python - 如何阻止 tempfile.NamedTemporaryFile 在临时文件前缀末尾添加随机字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61263301/

相关文章:

python - 在 Python 和 Perl 套接字之间交换数据

python - 如何使用 http 打破 flask 和 python 的无限循环?

python - 使用 webhook 向 Google Hangouts Chat 机器人发送简单消息

python - 如何读取没有标题或 mimetype 的 Gzip 字符串?使用 Python

python - 类型错误 :enqueuqe takes 1 positional argument but 2 were passed

python - 为什么 "a == x or y or z"总是评估为 True?如何将 "a"与所有这些进行比较?

python - split headless 选项被拒绝

python - Python多线程编程有什么优势?

python - 确定生成器产生的值的数量

python-3.x - 使用influxdb-python的Influxdb批量插入