locker.py 596 B

12345678910111213141516171819202122232425262728293031
  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. """ A lockfile that can be used as a context manager
  12. """
  13. def __init__(self, path, on_error=None):
  14. self.path = Path(path)
  15. self.on_error = on_error
  16. def __enter__(self):
  17. if self.path.exists():
  18. self.on_error() if self.on_error is not None else on_error()
  19. self.path.touch()
  20. def __exit__(self, type, value, traceback):
  21. self.path.remove()