mirror of
ssh://git.janware.com/srv/git/janware/proj/jw-python
synced 2026-01-15 09:53:32 +01:00
Eliminate a far chance of an exception thrown during process cleanup. Signed-off-by: Jan Lindemann <jan@janware.com>
40 lines
1,007 B
Python
40 lines
1,007 B
Python
import os, errno
|
|
import atexit
|
|
import tempfile
|
|
|
|
_tmpfiles = set()
|
|
|
|
def _cleanup():
|
|
for f in _tmpfiles:
|
|
silentremove(f)
|
|
|
|
def silentremove(filename): #export
|
|
try:
|
|
os.remove(filename)
|
|
except OSError as e:
|
|
if e.errno != errno.ENOENT:
|
|
raise # re-raise exception if a different error occurred
|
|
|
|
def pad(token, total_size, right_align = False):
|
|
add = total_size - len(token)
|
|
if add <= 0:
|
|
return token
|
|
space = ' ' * add
|
|
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)
|