我已将代码添加到 Python 包 ( brian2
) 中,该包在文件上放置了排他锁以防止出现竞争条件。但是,由于此代码包含对 的调用fcntl
,因此它不适用于 Windows。有没有办法让我在不安装新软件包的情况下对 Windows 中的文件进行独占锁定,例如pywin32
?(我不想向 . 添加依赖项brian2
。)
问问题
4239 次
1 回答
5
由于msvcrt是标准库的一部分,我假设您拥有它。msvcrt(MicroSoft Visual C 运行时)模块仅实现了 MS RTL 中可用的少数例程,但它确实实现了文件锁定。这是一个例子:
import msvcrt, os, sys
REC_LIM = 20
pFilename = "rlock.dat"
fh = open(pFilename, "w")
for i in range(REC_LIM):
# Here, construct data into "line"
start_pos = fh.tell() # Get the current start position
# Get the lock - possible blocking call
msvcrt.locking(fh.fileno(), msvcrt.LK_RLCK, len(line)+1)
fh.write(line) # Advance the current position
end_pos = fh.tell() # Save the end position
# Reset the current position before releasing the lock
fh.seek(start_pos)
msvcrt.locking(fh.fileno(), msvcrt.LK_UNLCK, len(line)+1)
fh.seek(end_pos) # Go back to the end of the written record
fh.close()
所示示例具有与 for 类似的功能fcntl.flock()
,但代码非常不同。仅支持独占锁。不像fcntl.flock()
没有开始参数(或来源)。lock 或 unlock 调用仅对当前文件位置进行操作。这意味着为了解锁正确的区域,我们必须将当前文件位置移回我们进行读取或写入之前的位置。解锁后,我们现在必须再次推进文件位置,回到读取或写入后的位置,这样我们才能继续。
如果我们解锁一个我们没有锁定的区域,那么我们不会收到错误或异常。
于 2015-05-25T14:50:59.270 回答