2017-07-25 17:06:03 +02:00
|
|
|
import os, errno
|
2017-11-22 09:33:18 +01:00
|
|
|
import atexit
|
|
|
|
|
import tempfile
|
2020-04-05 16:53:12 +02:00
|
|
|
import inspect
|
|
|
|
|
from jwutils import log
|
2017-11-22 09:33:18 +01:00
|
|
|
|
|
|
|
|
_tmpfiles = set()
|
|
|
|
|
|
|
|
|
|
def _cleanup():
|
|
|
|
|
for f in _tmpfiles:
|
2017-11-22 09:52:22 +01:00
|
|
|
silentremove(f)
|
2017-07-25 17:06:03 +02:00
|
|
|
|
|
|
|
|
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
|
2017-10-30 10:00:25 +01:00
|
|
|
|
|
|
|
|
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
|
2017-11-22 09:33:18 +01:00
|
|
|
|
|
|
|
|
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)
|
|
|
|
|
|
2019-10-24 18:45:05 +02:00
|
|
|
# see https://stackoverflow.com/questions/2020014
|
|
|
|
|
def object_builtin_name(o, full=True): # export
|
|
|
|
|
#if not full:
|
|
|
|
|
# return o.__class__.__name__
|
|
|
|
|
module = o.__class__.__module__
|
|
|
|
|
if module is None or module == str.__class__.__module__:
|
|
|
|
|
return o.__class__.__name__ # Avoid reporting __builtin__
|
|
|
|
|
return module + '.' + o.__class__.__name__
|
|
|
|
|
|
2020-04-05 16:53:12 +02:00
|
|
|
def get_derived_classes(mod, base): # export
|
|
|
|
|
members = inspect.getmembers(mod, inspect.isclass)
|
|
|
|
|
r = []
|
|
|
|
|
for name, c in members:
|
|
|
|
|
log.slog(log.DEBUG, "found ", name)
|
|
|
|
|
if inspect.isabstract(c):
|
|
|
|
|
log.slog(log.DEBUG, " is abstract")
|
|
|
|
|
continue
|
|
|
|
|
if not base in inspect.getmro(c):
|
|
|
|
|
log.slog(log.DEBUG, " is not derived from", base, "only", inspect.getmro(c))
|
|
|
|
|
continue
|
|
|
|
|
r.append(c)
|
|
|
|
|
return r
|
|
|
|
|
|
2017-11-22 09:33:18 +01:00
|
|
|
atexit.register(_cleanup)
|