forked from emscripten-core/emscripten
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtempfiles.py
More file actions
66 lines (58 loc) · 1.67 KB
/
tempfiles.py
File metadata and controls
66 lines (58 loc) · 1.67 KB
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
56
57
58
59
60
61
62
63
64
65
66
import os
import shutil
import tempfile
import atexit
import stat
def try_delete(filename):
try:
os.unlink(filename)
except:
pass
if not os.path.exists(filename): return
try:
shutil.rmtree(filename, ignore_errors=True)
except:
pass
if not os.path.exists(filename): return
try:
os.chmod(filename, os.stat(filename).st_mode | stat.S_IWRITE)
def remove_readonly_and_try_again(func, path, exc_info):
if not (os.stat(path).st_mode & stat.S_IWRITE):
os.chmod(path, os.stat(path).st_mode | stat.S_IWRITE)
func(path)
else:
raise
shutil.rmtree(filename, onerror=remove_readonly_and_try_again)
except:
pass
class TempFiles:
def __init__(self, tmp, save_debug_files=False):
self.tmp = tmp
self.save_debug_files = save_debug_files
self.to_clean = []
atexit.register(self.clean)
def note(self, filename):
self.to_clean.append(filename)
def get(self, suffix):
"""Returns a named temp file with the given prefix."""
named_file = tempfile.NamedTemporaryFile(dir=self.tmp, suffix=suffix, delete=False)
self.note(named_file.name)
return named_file
def get_dir(self):
"""Returns a named temp file with the given prefix."""
directory = tempfile.mkdtemp(dir=self.tmp)
self.note(directory)
return directory
def clean(self):
if self.save_debug_files:
import sys
print >> sys.stderr, 'not cleaning up temp files since in debug-save mode, see them in %s' % (self.tmp,)
return
for filename in self.to_clean:
try_delete(filename)
self.to_clean = []
def run_and_clean(self, func):
try:
return func()
finally:
self.clean()