Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, how do I make a temp file that persists until the next run?

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

Currently, I'm doing the following to create the directory:

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

And when I want to delete the directory, I just look for a directory with "temp" in it.
This seems like a dirty hack, but I'm not sure of a better way at the moment.

Incidentally, the reason that I need the folder around is that I start a process that uses the folder with the following:

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

and then quit my script to let the other process finish the work.

like image 355
John Mulder Avatar asked Nov 27 '22 02:11

John Mulder


1 Answers

Creating the folder with a 4-digit random number is insecure, and you also need to worry about collisions with other instances of your program.

A much better way is to create the folder using tempfile.mkdtemp, which does exactly what you want (i.e. the folder is not deleted when your script exits). You would then pass the folder name to the second Popen'ed script as an argument, and it would be responsible for deleting it.

like image 87
dF. Avatar answered Dec 18 '22 14:12

dF.