-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathtmpfile.py
55 lines (40 loc) · 1.47 KB
/
tmpfile.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# This is kind of an in between for tempfile and the program
# because it's hard/annoying to track all temp file references
# in the program itself
import tempfile
import os
import shutil
temp_filenames = []
temp_foldernames = []
def add_temp_file(filename):
temp_filenames.append(filename)
def add_temp_folder(filename):
temp_foldernames.append(filename)
def mkstemp(suffix=""):
os.makedirs("temp", exist_ok=True)
fid, filename = tempfile.mkstemp(suffix=suffix, dir="temp")
os.fdopen(fid, "w").close() # Fix bug with Windows
# Get relative path
if filename.startswith(os.path.abspath(".")):
filename = filename[len(os.path.abspath("."))+1:]
#print("Made temp file", filename)
temp_filenames.append(filename)
return filename
def mkdtemp(prefix=None):
os.makedirs("temp", exist_ok=True)
foldername = tempfile.mkdtemp(prefix=prefix, dir="temp")
# Get relative path
if foldername.startswith(os.path.abspath(".")):
foldername = foldername[len(os.path.abspath("."))+1:]
#print("Made temp folder", foldername)
temp_foldernames.append(foldername)
return foldername
def tmpcleanup():
for filename in temp_filenames:
if os.path.exists(filename):
#print("Removing temp file", filename)
os.remove(filename)
for foldername in temp_foldernames:
if os.path.exists(foldername):
#print("Removing temp folder", foldername)
shutil.rmtree(foldername)