Locking a file in Python

后端 未结 13 2547
悲&欢浪女
悲&欢浪女 2020-11-22 03:00

I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as

13条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 03:59

    The scenario is like that: The user requests a file to do something. Then, if the user sends the same request again, it informs the user that the second request is not done until the first request finishes. That's why, I use lock-mechanism to handle this issue.

    Here is my working code:

    from lockfile import LockFile
    lock = LockFile(lock_file_path)
    status = ""
    if not lock.is_locked():
        lock.acquire()
        status = lock.path + ' is locked.'
        print status
    else:
        status = lock.path + " is already locked."
        print status
    
    return status
    

提交回复
热议问题