misc.py: Add atomic_store()

Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
Jan Lindemann 2017-11-22 09:33:18 +01:00
commit 4a200c8851

View file

@ -1,4 +1,12 @@
import os, errno
import atexit
import tempfile
_tmpfiles = set()
def _cleanup():
for f in _tmpfiles:
os.unlink(f)
def silentremove(filename): #export
try:
@ -15,3 +23,18 @@ def pad(token, total_size, right_align = False):
if right_align:
return space + token
return token + space
def atomic_store(contents, path): # export
if path[0:3] == '/dev':
with open(path, 'w') as outfile:
outfile.write(contents)
return
outfile = tempfile.NamedTemporaryFile(prefix=os.path.basename(path), delete=False, dir=os.path.dirname(path))
name = outfile.name
_tmpfiles.add(name)
outfile.write(contents)
outfile.close()
os.rename(name, path)
_tmpfiles.remove(name)
atexit.register(_cleanup)