comparison env/lib/python3.9/site-packages/galaxy/util/renamed_temporary_file.py @ 0:4f3585e2f14b draft default tip

"planemo upload commit 60cee0fc7c0cda8592644e1aad72851dec82c959"
author shellac
date Mon, 22 Mar 2021 18:12:50 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:4f3585e2f14b
1 """Safely write file to temporary file and then move file into place."""
2 # Copied from https://stackoverflow.com/a/12007885.
3 import os
4 import tempfile
5
6
7 class RenamedTemporaryFile:
8 """
9 A temporary file object which will be renamed to the specified
10 path on exit.
11 """
12 def __init__(self, final_path, **kwargs):
13 """
14 >>> dir = tempfile.mkdtemp()
15 >>> with RenamedTemporaryFile(os.path.join(dir, 'test.txt'), mode="w") as out:
16 ... _ = out.write('bla')
17 """
18 tmpfile_dir = kwargs.pop('dir', None)
19
20 # Put temporary file in the same directory as the location for the
21 # final file so that an atomic move into place can occur.
22
23 if tmpfile_dir is None:
24 tmpfile_dir = os.path.dirname(final_path)
25
26 self.tmpfile = tempfile.NamedTemporaryFile(dir=tmpfile_dir, delete=False, **kwargs)
27 self.final_path = final_path
28
29 def __getattr__(self, attr):
30 """
31 Delegate attribute access to the underlying temporary file object.
32 """
33 return getattr(self.tmpfile, attr)
34
35 def __enter__(self):
36 self.tmpfile.__enter__()
37 return self
38
39 def __exit__(self, exc_type, exc_val, exc_tb):
40 if exc_type is None:
41 self.tmpfile.flush()
42 result = self.tmpfile.__exit__(exc_type, exc_val, exc_tb)
43 os.rename(self.tmpfile.name, self.final_path)
44 else:
45 result = self.tmpfile.__exit__(exc_type, exc_val, exc_tb)
46
47 return result