Because I didn't see a good implementation, I've posted here my own implementation of a lockfile context manager. It's POSIX-only because I don't have a Windows machine to test cross-platform atomicity on. Sorry about that.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
import contextlib, errno, os, time @contextlib.contextmanager def flock(path, wait_delay=.1): while True: try: fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_RDWR) except OSError, e: if e.errno != errno.EEXIST: raise time.sleep(wait_delay) continue else: break try: yield fd finally: os.unlink(path)
with flock('.lockfile'): # do whatever.
If you want to actually use the file descriptor, 'as' and 'fdopen' are all you need:
with flock('.lockfile') as fd: lockfile = os.fdopen(fd, 'r+')