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

2024-06-16 14:52:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经将code添加到Python包(^{})中,该包在文件上放置独占锁,以防止出现争用情况。但是,由于此代码包含对fcntl的调用,因此它在Windows上不起作用。我有没有办法在不安装新软件包的情况下对Windows中的文件进行独占锁定,比如pywin32?(我不想向brian2添加依赖项。)


Tags: 文件代码windows情况codebrian2pywin32办法
1条回答
网友
1楼 · 发布于 2024-06-16 14:52:47

由于msvcrt是标准库的一部分,我假设您已经拥有了它。msvcrt(microsoftvisualc运行时)模块只实现了msrtl中可用的少量例程,但是它实现了文件锁定。 下面是一个例子:

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()

所示的示例具有与fcntl.flock()相似的函数,但是代码非常不同。只支持独占锁。 与fcntl.flock()不同的是,没有起始参数(或从何而来)。锁定或解锁调用仅对当前文件位置起作用。这意味着,为了解锁正确的区域,我们必须将当前文件位置移回读取或写入之前的位置。解锁后,我们现在必须再次推进文件位置,回到读或写之后的位置,这样我们就可以继续了。在

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

相关问题 更多 >