python 文件锁模块删除文件

python filelock module deleting files

我已经下载了 filelock 模块,以便使用我的 python 程序锁定文件。 这是我的代码:

import filelock
lock = filelock.FileLock(path)
lock.acquire()
#do something...
lock.release()

出于某种原因我不明白当我释放锁时文件被删除了。 有谁知道如何处理这个?释放锁后如何保持文件可用? 如果相关,我的文件保存在单独的硬盘上。 谢谢。

我正在使用 windows 10 pro

我不确定为什么,但文档表明它不应该做你正在经历的事情。但是如果你是在windows上使用这个,你可以看看release lock的实现,你会发现如果是最终锁或者强行释放锁,确实会删除文件。请查看“Windows locking mechanism”部分。

windows 锁定的底层实现使用以下发布代码:

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

如您所见,os.remove 将删除该文件。尽管这无济于事,但希望能解释为什么会这样。可能是错误或有人忘记删除的陈旧代码。

这对我 Windows 有用,对你也应该有用 benediktschmitt

Hi,

the use case for this library is signalizing different instances of an application, that shared resources are currently accessed. For example: Some synchronization programs create a lock file during synchronization in the root folder to prevent other instances from doing it to the same time. As soon as the lock file has been removed, the other instance starts the synchronization progress.

If you want to avoid race conditions, you can use either this library like this:

lock = FileLock(flnm + ".lock") with lock.acquire(timeout=5):<br> with open(flnm, "a") as file: file.write("some text")

or you take a look at the underlying os functions: https://www.safaribooksonline.com/library/view/python-cookbook/0596001673/ch04s25.html

EDIT: Removing the file is done intentionally as part of the clean up.