如何在不安装新软件包的情况下在 Windows 上执行文件锁定

dbl*_*iss 6 python locking pywin32 fcntl

我已将代码添加到 Python 包 ( brian2) 中,该包在文件上放置了排他锁以防止出现竞争条件。但是,由于此代码包含对 的调用fcntl,因此它不适用于 Windows。有没有办法让我在不安装新软件包的情况下对 Windows 中的文件设置独占锁,比如pywin32?(我不想向 . 添加依赖项brian2。)

cda*_*rke 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()
Run Code Online (Sandbox Code Playgroud)

显示的示例具有与 for 类似的功能fcntl.flock(),但代码非常不同。仅支持独占锁。fcntl.flock()与没有开始参数(或从哪里开始)不同。锁定或解锁调用仅对当前文件位置进行操作。这意味着为了解锁正确的区域,我们必须将当前文件位置移回到进行读取或写入之前的位置。解锁后,我们现在必须再次前进文件位置,回到读取或写入后的位置,以便我们可以继续。

如果我们解锁一个没有锁的区域,那么我们不会收到错误或异常。