How to perform file-locking on Windows without installing a new package

后端 未结 1 442
渐次进展
渐次进展 2021-01-19 15:26

I\'ve added code to a Python package (brian2) that places an exclusive lock on a file to prevent a race condition. However, because this code includes calls to fcntl<

1条回答
  •  北恋
    北恋 (楼主)
    2021-01-19 15:53

    Since msvcrt is part of the standard library, I assume you have it. The msvcrt (MicroSoft Visual C Run Time) module only implements a small number of the routines available in the MS RTL, however it does implement file locking. Here is an example:

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

    The example shown has a similar function as for fcntl.flock(), however the code is very different. Only exclusive locks are supported. Unlike fcntl.flock() there is no start argument (or whence). The lock or unlock call only operates on the current file position. This means that in order to unlock the correct region we have to move the current file position back to where it was before we did the read or write. Having unlocked, we now have to advance the file position again, back to where we were after the read or write, so we can proceed.

    If we unlock a region for which we have no lock then we do not get an error or exception.

    0 讨论(0)
提交回复
热议问题