0

I have multiple python apps/scripts witch i'd like to write/read to/from the same file. For example block if file is open. Is it possible to make this safe and deadlock free. I use windows and python2.

abalcerek
  • 1,807
  • 1
  • 22
  • 27
  • 2
    related: [Locking a file in Python](http://stackoverflow.com/q/489861/4279). You probably wants to use a real database instead of a flat file if you want to write data reliably into the same place from multiple processes (It may fix issues you didn't even know you had). Related: [Logging to a single file from multiple processes](https://docs.python.org/dev/howto/logging-cookbook.html#logging-to-a-single-file-from-multiple-processes) – jfs Dec 25 '15 at 22:36
  • @J.F.Sebastian This question indeed contains plenty of good answer and mine should probably be closed as duplicate. For some reason google search didn't find it. I think I should not delete it because it is already answered. – abalcerek Dec 25 '15 at 22:51

1 Answers1

1

Here is a module for platform-independent file locking https://pypi.python.org/pypi/filelock/

Here is the relevant code from that module for performing the file lock on Windows.

class WindowsFileLock(BaseFileLock):
"""
Uses the :func:`msvcrt.locking` function to hard lock the lock file on
windows systems.
"""

def _acquire(self):
    open_mode = os.O_RDWR | os.O_CREAT | os.O_TRUNC

    try:
        fd = os.open(self._lock_file, open_mode)
    except OSError:
        pass
    else:
        try:
            msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
        except (IOError, OSError):
            os.close(fd)
        else:
            self._lock_file_fd = fd
    return None

def _release(self):
    msvcrt.locking(self._lock_file_fd, msvcrt.LK_UNLCK, 1)
    os.close(self._lock_file_fd)
    self._lock_file_fd = None

    try:
        os.remove(self._lock_file)
    # Probably another instance of the application
    # that acquired the file lock.
    except OSError:
        pass
    return None

I'm still trying to figure out how exactly this functionality is implemented ... but Windows does provide an API for acquiring a lock on a file.

https://msdn.microsoft.com/en-us/library/windows/desktop/aa365203%28v=vs.85%29.aspx

Greg Nisbet
  • 6,710
  • 3
  • 25
  • 65