Skip to content

Instantly share code, notes, and snippets.

@lonetwin
Last active December 8, 2022 08:05
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lonetwin/7b4ccc93241958ff6967 to your computer and use it in GitHub Desktop.
Save lonetwin/7b4ccc93241958ff6967 to your computer and use it in GitHub Desktop.
Simple python file locking context manager example on linux using python stdlib's `fcntl.flock`
import logging
import fcntl
from contextlib import contextmanager
@contextmanager
def locked_open(filename, mode='r'):
"""locked_open(filename, mode='r') -> <open file object>
Context manager that on entry opens the path `filename`, using `mode`
(default: `r`), and applies an advisory write lock on the file which
is released when leaving the context. Yields the open file object for
use within the context.
Note: advisory locking implies that all calls to open the file using
this same api will block for both read and write until the lock is
acquired. Locking this way will not prevent the file from access using
any other api/method.
"""
with open(filename, mode) as fd:
fcntl.flock(fd, fcntl.LOCK_EX)
logging.debug('acquired lock on %s', filename)
yield fd
# raw_input('press enter to release lock ')
logging.debug('releasing lock on %s', filename)
fcntl.flock(fd, fcntl.LOCK_UN)
@lonetwin
Copy link
Author

Typos: contexlib/contexmanager => contextlib/contextmanager

Nice gist!

cheers, thanks for reporting that !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment