class token(): ''' Poor man's interprocess lock To use from another module: with baton.token() as t: do_something() The token will be release when comming out of the "with". ''' filename = '/var/lock/my.token' delay = 2 def __init__(self): self.gotit = False self.get() def get(self): import os import sys import logging import random import time if not self.gotit: pid = os.getpid() while True: try: fd = os.open(self.filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL) except OSError as err: if err.errno == 17: logging.info('waiting for token') time.sleep(random.randrange(1,10)) continue else: # e.g.: a permission issue raise break f = os.fdopen(fd, 'w') f.writelines('pid: ' + str(pid) + '\n') f.close() self.gotit = True def release(self): import os import time import logging if self.gotit: logging.debug('releasing token') time.sleep(self.delay) os.unlink(self.filename) self.gotit = False def __del__(self): self.release() def __enter__(self): return self def __exit__(self, type, value, traceback): self.release() # We don't care if / why the calling value failed, we need to # get rid of the token. return True