In Python, how do I create a temporary file that persists until the next run?

I need to create a folder that I use only once, but I need it to exist until the next start. It looks like I should use the tmp_file module in the standard library, but I'm not sure how to get the behavior that I want.

Currently, to create a directory, I am doing the following:

randName = "temp" + str(random.randint(1000, 9999))
os.makedirs(randName)

And when I want to delete a directory, I am just looking for a directory with "temp" in it.
This seems like a dirty hack, but so far I'm not sure about the best way.

By the way, the reason I need a folder is because I am running a process that uses a folder with the following:

subprocess.Popen([command], shell=True).pid

and then close my script so that another process exits.

+3
7

4- , .

tempfile.mkdtemp, , (.. , script). Popen'ed script , .

+16

, , . , - , . , -, "temp", , . , tempfile.mkdtemp, , . , , .

import tempfile
import shutil
import subprocess

d = tempfile.mkdtemp(prefix='tmp')
try:
    subprocess.check_call(['/bin/echo', 'Directory:', d])
finally:
    shutil.rmtree(d)
+8

" , , , ".

", , , , ..."

, . .

, .

mkdir someDirectory
proc1 -o someDirectory # Write to the directory
proc2 -i someDirectory # Read from the directory
if [ %? == 0 ]
then
    rm someDirectory
fi

, ?

, , Python .

  • , ( "proc1" "proc2" )

  • , ; , Python bash script.

+4

, .

.

, - - temp , , .

, /tmp .

+3

, ( ), :

import atexit
import shutil
import tempfile

# create your temporary directory
d = tempfile.mkdtemp()

# suppress it when python will be closed
atexit.register(lambda: shutil.rmtree(d))

# do your stuff...
subprocess.Popen([command], shell=True).pid
+2

tempfile , , - , , . . /tmp , tempfile.mkdtemp dir . , , , .

+1

- tempName.TemporaryFile(mode = 'w + b', suffix = '. tmp', prifix = 'someRandomNumber' dir = None) mktemp().

mktemp() , ( PID).

+1

Source: https://habr.com/ru/post/1703736/


All Articles