Skip to content

Instantly share code, notes, and snippets.

@baverman
Created May 25, 2018 04:58
Show Gist options
  • Select an option

  • Save baverman/f5d4acb1a2c27974747d36095b4b915a to your computer and use it in GitHub Desktop.

Select an option

Save baverman/f5d4acb1a2c27974747d36095b4b915a to your computer and use it in GitHub Desktop.

Revisions

  1. baverman revised this gist May 25, 2018. No changes.
  2. baverman created this gist May 25, 2018.
    20 changes: 20 additions & 0 deletions file_lock.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    @contextmanager
    def lock(file_name, block=False):
    fp = open(file_name, 'w')

    opts = fcntl.LOCK_EX
    if not block:
    opts |= fcntl.LOCK_NB

    try:
    fcntl.lockf(fp, opts)
    except IOError:
    if block:
    raise
    yield False
    else:
    try:
    yield True
    finally:
    fcntl.lockf(fp, fcntl.LOCK_UN)
    fp.close()