""" Lockfile utility @author: olivier.massot, 05-2020 """ from path import Path class AlreadyRunning(RuntimeError): pass def on_error(): raise AlreadyRunning class Lockfile: """ A lockfile that can be used as a context manager """ def __init__(self, path, on_error=None): self.path = Path(path) self.on_error = on_error def __enter__(self): if self.path.exists(): self.on_error() if self.on_error is not None else on_error() self.path.touch() def __exit__(self, type, value, traceback): self.path.remove()