import os class Lockfile: """Prevent unwanted concurrency for file I/O. For a file named "", create or remove a lockfile named ".lock". When a process is modifying the file, call `lock(). When the modification is done, call `unlock()`. """ def __init__(self, filepath): self.filepath = filepath self.lockpath = filepath + ".lock" def lock(self): """Continue attempting to lock until locked.""" locked = False while not locked: try: f = open(self.lockpath, "x") f.close() locked = True except FileExistsError: continue def unlock(self): """Remove lockfile.""" try: os.remove(self.lockpath) except FileNotFoundError: return