Locking a file in Python

后端 未结 13 2315
悲&欢浪女
悲&欢浪女 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:46

    You may find pylocker very useful. It can be used to lock a file or for locking mechanisms in general and can be accessed from multiple Python processes at once.

    If you simply want to lock a file here's how it works:

    import uuid
    from pylocker import Locker
    
    #  create a unique lock pass. This can be any string.
    lpass = str(uuid.uuid1())
    
    # create locker instance.
    FL = Locker(filePath='myfile.txt', lockPass=lpass, mode='w')
    
    # aquire the lock
    with FL as r:
        # get the result
        acquired, code, fd  = r
    
        # check if aquired.
        if fd is not None:
            print fd
            fd.write("I have succesfuly aquired the lock !")
    
    # no need to release anything or to close the file descriptor, 
    # with statement takes care of that. let's print fd and verify that.
    print fd
    

提交回复
热议问题