我需要使用Windows方法本地锁定文件。目前,我在一个程序中有:
msvcrt.locking(fh.fileno(), msvcrt.LK_LOCK, os.stat(fh.name).st_size)
这将锁定整个文件以供读取,如下所示:
fh = open(f, 'rb')
msvcrt.locking(fh.fileno(), msvcrt.LK_LOCK, os.stat(fh.name).st_size)
ffh = open(f, 'rb')
print(next(ffh))
# PermissionError: [Errno 13] Permission denied
但是,如果我要打开文件进行写入,则文件将被截断。
如果文件已经被另一个进程打开,如何防止其打开?
从这里的另一篇文章中,我有一个解决方案(也许没有)
def lock_test(path):
"""
Checks if a file can, aside from it's permissions, be changed right now (True)
or is already locked by another process (False).
:param str path: file to be checked
:rtype: bool
"""
import msvcrt
try:
fd = os.open(path, os.O_APPEND | os.O_EXCL | os.O_RDWR)
except OSError:
return False
try:
msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
os.close(fd)
return True
except (OSError, IOError):
os.close(fd)
return False
指向解决方案的链接How to test file locking in Python