Detect and delete locked file in python

后端 未结 3 1742
感情败类
感情败类 2021-02-10 16:57

I want to detect whether a file is locked, using python on Unix. It\'s OK to delete the file, assuming that it helps detects whether the file was locked.

The file could

相关标签:
3条回答
  • 2021-02-10 17:17

    The best way to check if a file is locked is to try to lock it. The fcntl module will do this in Python, e.g.

    fcntl.lockf(fileobj.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)

    This will raise an IOError if the file is already locked; if it doesn't, you can then call

    fcntl.lockf(fileobj.fileno(), fcntl.LOCK_UN)

    To unlock it again.

    Note that unlike Windows, opening a file for writing does not automatically give you an exclusive lock in Unix. Also note that the fcntl module is not available on Windows; you'll need to use os.open, which is a much less friendly but more portable interface (and may require re-opening the file again).

    0 讨论(0)
  • 2021-02-10 17:18

    From the fcntl docs:

    fcntl.lockf(fd, operation[, length[, start[, whence]]])

    If LOCK_NB is used and the lock cannot be acquired, an IOError will be raised and the exception will have an errno attribute set to EACCES or EAGAIN (depending on the operating system; for portability, check for both values).

    This uses the underlying unix flock mechanism, so looks like it should do what you want. Also note there is also os.open, which may be more platform-independent.

    0 讨论(0)
  • 2021-02-10 17:28

    I tried to lock a file in mac and delete the same file in another terminal. It allows the file to be deleted.

    lock_file_path = "/tmp/lock.file"
    fd = open(lock_file_path,"w")
    fcntl.flock(fd.fileno(),LOCK_EX)
    while True:
        print("Locked")
    
    0 讨论(0)
提交回复
热议问题