简体   繁体   中英

python filelock module deleting files

I have downloaded the filelock module in order to lock files using my python program. this is my code:

import filelock
lock = filelock.FileLock(path)
lock.acquire()
#do something...
lock.release()

for some reason I don't understand when I release the lock the file is deleted. Does anyone know how to deal with this? How can I keep the file available also after the lock is released? if it is relevant, my file is kept on a separate hard drive. thank you.

I am using windows 10 pro

I am not sure why but the documentation suggests that it should not do what you are experiencing. However if you are using this on windows, you can look at the implementation of release lock and you will realise that it will indeed delete the file if it is the final lock or if the lock is forcefully released. Please have a look at the section for the " Windows locking mechanism ".

The underlying implementation for windows locking uses the following release code:

def _release(self):
    msvcrt.locking(self._lock_file_fd, msvcrt.LK_UNLCK, 1)
    os.close(self._lock_file_fd)
    self._lock_file_fd = None

    try:
        os.remove(self._lock_file)
    # Probably another instance of the application
    # that acquired the file lock.
    except OSError:
        pass
    return None

As you can see the os.remove will delete the file. Even though this does not help but hopefully explains why this is happening. Could be a bug or stale code somebody forgot to remove.

This worked for me in Windows and should also work for you benediktschmitt

Hi,

the use case for this library is signalizing different instances of an application, that shared resources are currently accessed. For example: Some synchronization programs create a lock file during synchronization in the root folder to prevent other instances from doing it to the same time. As soon as the lock file has been removed, the other instance starts the synchronization progress.

If you want to avoid race conditions, you can use either this library like this:

lock = FileLock(flnm + ".lock") with lock.acquire(timeout=5):
with open(flnm, "a") as file: file.write("some text")

or you take a look at the underlying os functions: https://www.safaribooksonline.com/library/view/python-cookbook/0596001673/ch04s25.html

EDIT: Removing the file is done intentionally as part of the clean up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM