locker.py 529 B

123456789101112131415161718192021222324252627
  1. """
  2. Lockfile utility
  3. @author: olivier.massot, 05-2020
  4. """
  5. from path import Path
  6. class AlreadyRunning(RuntimeError):
  7. pass
  8. def on_error():
  9. raise AlreadyRunning
  10. class Lockfile:
  11. def __init__(self, path, on_error=None):
  12. self.path = Path(path)
  13. self.on_error = on_error
  14. def __enter__(self):
  15. if self.path.exists():
  16. self.on_error() if self.on_error is not None else on_error()
  17. self.path.touch()
  18. def __exit__(self, type, value, traceback):
  19. self.path.remove()