@contextmanager
def lock_file(filename, timeout=10, append=False, unlink=True):
 flags = (os.O_CREAT | os.O_RDWR)
 if append:
  flags |= os.O_APPEND
  mode = 'a+'
 else:
  mode = 'r+'
 fd = os.open(filename, flags)
 file_obj = os.fdopen(fd, mode)
 try:
  with LockTimeout(timeout, filename):
   while True:
    try:
     fcntl.flock(fd, (fcntl.LOCK_EX | fcntl.LOCK_NB))
     break
    except IOError as err:
     if (err.errno != errno.EAGAIN):
      raise
    sleep(0.01)
  (yield file_obj)
 finally:
  try:
   file_obj.close()
  except UnboundLocalError:
   pass
  if unlink:
   os.unlink(filename)

@ contextmanager def lock_file ( filename , timeout = 10 , append = False , unlink = True ) : flags = ( os . O_CREAT | os . O_RDWR ) if append : flags |= os . O_APPEND mode = 'a+' else : mode = 'r+' fd = os . open ( filename , flags ) file_obj = os . fdopen ( fd , mode ) try : with LockTimeout ( timeout , filename ) : while True : try : fcntl . flock ( fd , ( fcntl . LOCK_EX | fcntl . LOCK_NB ) ) break except IOError as err : if ( err . errno != errno . EAGAIN ) : raise sleep ( 0.01 ) ( yield file_obj ) finally : try : file_obj . close ( ) except UnboundLocalError : pass if unlink : os . unlink ( filename )
context manager that acquires a lock on a file .