13

我的目标是知道文件是否被另一个进程锁定,即使我无权访问该文件!

open()所以更清楚地说,假设我正在使用python 的内置'wb'开关(用于写入)打开文件。open()如果:IOError_errno 13 (EACCES)

  1. 用户无权访问该文件或
  2. 该文件被另一个进程锁定

我怎样才能在这里检测到案例(2)?

(我的目标平台是 Windows)

4

3 回答 3

6

您可以os.access用于检查您的访问权限。如果访问权限很好,那么它必须是第二种情况。

于 2012-11-14T00:58:45.320 回答
5

正如前面评论中所建议的,os.access不返回正确的结果。

但是我在网上找到了另一个确实有效的代码。诀窍是它试图重命名文件。

来自: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
于 2020-09-06T05:56:59.990 回答
3

根据文档:

errno.EACCES
    Permission denied
errno.EBUSY

    Device or resource busy

所以只需这样做:

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

从那里找出 errno 代码,就可以了。

于 2012-11-14T00:59:05.430 回答