Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : Check file is locked

Tags:

python

file-io

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)

like image 239
Ali Avatar asked Nov 14 '12 00:11

Ali


3 Answers

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

like image 93
Harman Avatar answered Oct 13 '22 22:10

Harman


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
like image 26
paolov Avatar answered Oct 13 '22 23:10

paolov


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.

like image 3
PearsonArtPhoto Avatar answered Oct 13 '22 22:10

PearsonArtPhoto