10
votes

My goal is to know if a file is locked by another process or not, even if I don't have access to that file!

So to be more clear, let's say I'm opening the file using python's built-in open() with 'wb' switch (for writing). open() will throw IOError with errno 13 (EACCES) if:

  1. the user does not have permission to the file or
  2. the file is locked by another process

How can I detect case (2) here?

(My target platform is Windows)

3
Once you've determined the user has permissions and you still get the exception then you know case (2) has been hit. - monkut
Do you know how the other process is locking the file? It seems like there are multiple ways to do it. - Sam Mussmann
Suppose you get an answer to this question; what do you propose to do with the information? - Karl Knechtel
@KarlKnechtel report the proper response to the user. - Ali

3 Answers

6
votes

You can use os.access for checking your access permission. If access permissions are good, then it has to be the second case.

3
votes

According to the docs:

errno.EACCES
    Permission denied
errno.EBUSY

    Device or resource busy

So just do this:

try:
    fp = open("file")
except IOError as e:
    print e.errno
    print e

Figure out the errno code from there, and you're set.

2
votes

As suggested in earlier comments, os.access does not return the correct result.

But I found another code online that does work. The trick is that it attempts to rename the file.

From: https://blogs.blumetech.com/blumetechs-tech-blog/2011/05/python-file-locking-in-windows.html

def isFileLocked(filePath):
    '''
    Checks to see if a file is locked. Performs three checks
        1. Checks if the file even exists
        2. Attempts to open the file for reading. This will determine if the file has a write lock.
            Write locks occur when the file is being edited or copied to, e.g. a file copy destination
        3. Attempts to rename the file. If this fails the file is open by some other process for reading. The 
            file can be read, but not written to or deleted.
    @param filePath:
    '''
    if not (os.path.exists(filePath)):
        return False
    try:
        f = open(filePath, 'r')
        f.close()
    except IOError:
        return True

    lockFile = filePath + ".lckchk"
    if (os.path.exists(lockFile)):
        os.remove(lockFile)
    try:
        os.rename(filePath, lockFile)
        sleep(1)
        os.rename(lockFile, filePath)
        return False
    except WindowsError:
        return True