用Python同步文件写入



我有多个python应用程序/脚本,我想在同一个文件中写入/读取。例如,如果文件处于打开状态,则阻止。有没有可能让这个安全无死锁。我用窗户和蟒蛇。

这里有一个用于独立于平台的文件锁定的模块https://pypi.python.org/pypi/filelock/

以下是该模块中用于在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

我仍在努力弄清楚这个功能究竟是如何实现的。。。但是Windows确实提供了API来获取文件上的锁。

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

最新更新