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 have been originally opened exclusively by another process. Documentation seems to suggest that os.unlink won’t necessarily return an error if the file is locked.
Ideas?
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).