Python:检查文件已锁定

Ali*_*Ali 6 python file-io

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

所以更清楚一点,假设我使用python的内置open()和'wb'开关(用于写入)打开文件.open()将抛出IOError与errno 13(EACCES)if

  1. 用户没有该文件的权限或
  2. 该文件被另一个进程锁定

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

我的目标平台是Windows!

Har*_*man 6

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

  • 十年后,python [问题](https://bugs.python.org/issue2528) 仍然开放...... (4认同)
  • @Ali - 你是对的。os.access 在 Windows 中不返回正确的值。这是 python.org [http://bugs.python.org/issue2528] 上的问题。它还提供了一个补丁,但我不确定应用该补丁是否很简单。 (2认同)
  • 感谢您指出错误。显然使用win32security,在windows中很容易获得文件的ACL权限。 (2认同)

pao*_*lov 6

正如之前的评论中所建议的,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
Run Code Online (Sandbox Code Playgroud)