由于 msvcrt 是标准库的一部分,我认为您已经拥有了它。然而,msvcrt(MicroSoft Visual C Run Time)模块只实现了 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()
fcntl.flock()
具有类似的功能,但代码非常不同。仅支持独占锁。
与fcntl.flock()
不同,没有启动参数(或whence)。锁定或解锁调用仅对当前文件位置进行操作。这意味着为了解锁正确的区域,我们必须将当前文件位置移回读取或写入之前的位置。解锁后,我们现在必须再次推进文件位置,回到读取或写入后的位置,以便我们可以继续进行。
msvcrt
吗? - cdarkefcntl
? - abcdfcntl
在Windows上的Python 2或3中没有捆绑。 - cdarke