__init__.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. import logging
  2. import tempfile
  3. import time
  4. import os
  5. import shutil
  6. import contextlib
  7. import library.python.fs as fs
  8. import library.python.unique_id as uniq_id
  9. logger = logging.getLogger(__name__)
  10. _tmp_roots = []
  11. _startup_tmp_dir = None
  12. _startup_tmp_dir_set = False
  13. def set_tmp_dir(root, keep_dir):
  14. uniq_name = '{0}.{1}.{2}'.format(int(time.time()), os.getpid(), uniq_id.gen8())
  15. tmp_dir = os.path.join(root, uniq_name)
  16. fs.create_dirs(tmp_dir)
  17. old_tmp_dir = os.environ.get('TMPDIR')
  18. logger.debug('Set TMPDIR=%s instead of %s', tmp_dir, old_tmp_dir)
  19. os.environ['TMPDIR'] = tmp_dir
  20. global _startup_tmp_dir
  21. global _startup_tmp_dir_set
  22. if not _startup_tmp_dir_set:
  23. _startup_tmp_dir = old_tmp_dir
  24. _startup_tmp_dir_set = True
  25. if not keep_dir:
  26. _tmp_roots.append(tmp_dir)
  27. def remove_tmp_dirs(env=None):
  28. if env is None:
  29. env = os.environ
  30. global _tmp_roots
  31. for x in _tmp_roots:
  32. logger.debug('Removing tmp dir %s', x)
  33. shutil.rmtree(x, ignore_errors=True)
  34. _tmp_roots = []
  35. revert_tmp_dir(env)
  36. def revert_tmp_dir(env=None):
  37. if not env:
  38. env = os.environ
  39. if _startup_tmp_dir_set:
  40. if _startup_tmp_dir is not None:
  41. env['TMPDIR'] = _startup_tmp_dir
  42. else:
  43. env.pop('TMPDIR', None)
  44. logger.debug('Reset back TMPDIR=%s', env.get('TMPDIR'))
  45. def temp_path(path):
  46. class Remover(object):
  47. def __init__(self, path):
  48. self.path = path
  49. def __enter__(self):
  50. return self.path
  51. def __exit__(self, exc_type, exc_value, traceback):
  52. if _tmp_roots or not _startup_tmp_dir_set:
  53. fs.remove_tree_safe(path)
  54. return Remover(path)
  55. def create_temp_file(prefix='yatmp'):
  56. fd, path = tempfile.mkstemp(prefix=prefix)
  57. os.close(fd)
  58. return path
  59. def temp_dir(prefix='yatmp'):
  60. tmpdir = tempfile.mkdtemp(prefix=prefix)
  61. return temp_path(tmpdir)
  62. def temp_file(prefix='yatmp'):
  63. tmpfile = create_temp_file(prefix=prefix)
  64. return temp_path(tmpfile)
  65. @contextlib.contextmanager
  66. def environment(env):
  67. def set_env(e):
  68. os.environ.clear()
  69. for k, v in e.items():
  70. os.environ[k] = v
  71. stored = os.environ.copy()
  72. try:
  73. set_env(env or {})
  74. yield
  75. finally:
  76. set_env(stored)