简体   繁体   中英

How to stop tempfile.NamedTemporaryFile from adding random characters to the end of the temp file prefix?

I'm trying to make a temporary file that will last for the duration of my program. I want the user to be able to easily access this file in their chosen text editor.

Because of this, I'm wondering how I could get rid of the random characters that are appended to the end of the prefix in the temp file, NamedTemporaryFile? Because it makes harder for the user to type it.

Normally it is like this:

aDataSetn6jw9ehy.py

I would like it to work like this:

aDataSet.py

Unfortunately, at the moment this is only possible by jumping through hoops.

Internally, tempfile makes use of a _RandomNameSequence class, an iterator that generates random names. However, the size of each name is hard-coded to eight characters. To support shorter or longer names, or names with different qualities, you will have to use a custom name sequence. This random name will be incorporated into the temporary file name generated by NamedTemporaryFile ; giving a prefix or suffix will not change this name, but merely add to it.

When tempfile.NamedTemporaryFile is asked to generate a temporary file name, it calls tempfile._get_candidate_names() to retrieve a _RandomNameSequence iterator; it generates this iterator only once and stores it in a global variable. Currently, the only way to change what iterator is used is to change tempfile._get_candidate_names() to a different function, like this:

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

You can also return a custom random name generator as the iterator:

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

Then, you can create a NamedTemporaryFile setting the desired prefix of the temporary file; the "root" of the name will be then determined by the new iterator:

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

Again, all this is hoop-jumping, and this lack of a way to customize the random name sequence appears to show a shortcoming in the tempfile module; if this is something you care about, open a report in bugs.python.org .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM