@contextmanager
def lockfile(filename, shared=False):
 with open(filename, 'w') as lock:
  with flock(lock, shared=shared):
   (yield)

@ contextmanager def lockfile ( filename , shared = False ) : with open ( filename , 'w' ) as lock : with flock ( lock , shared = shared ) : ( yield )
lock a file using flock(2) for the duration of a with statement .