Detect and delete locked file in python

后端 未结 3 1745
感情败类
感情败类 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).

提交回复
热议问题