Python: Lock a file

前端 未结 5 546
心在旅途
心在旅途 2020-12-14 13:37

I have a Python app running on Linux. It is called every minute from cron. It checks a directory for files and if it finds one it processes it - this can take several minute

5条回答
  •  时光取名叫无心
    2020-12-14 14:25

    After fumbling with many schemes, this works in my case. I have a script that may be executed multiple times simultaneously. I need these instances to wait their turn to read/write to some files. The lockfile does not need to be deleted, so you avoid blocking all access if one script fails before deleting it.

    import fcntl
    
    def acquireLock():
        ''' acquire exclusive lock file access '''
        locked_file_descriptor = open('lockfile.LOCK', 'w+')
        fcntl.lockf(locked_file_descriptor, fcntl.LOCK_EX)
        return locked_file_descriptor
    
    def releaseLock(locked_file_descriptor):
        ''' release exclusive lock file access '''
        locked_file_descriptor.close()
    
    lock_fd = acquireLock()
    
    # ... do stuff with exclusive access to your file(s)
    
    releaseLock(lock_fd)
    

提交回复
热议问题