How to perform file-locking on Windows without installing a new package
我在python包(
因为MSVCRT是标准库的一部分,所以我假设您拥有它。MSVCRT(Microsoft Visual C运行时)模块仅实现MS RTL中的少量可用例程,但它确实实现了文件锁定。下面是一个例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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() |
所示示例具有与
如果我们解锁一个没有锁的区域,那么我们就不会得到错误或异常。