简体   繁体   English

Python:检查文件是否已锁定

[英]Python : Check file is locked

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).为了更清楚,假设我使用带有'wb'开关(用于写入)的python 内置open()文件。 open() will throw IOError with errno 13 (EACCES) if: open()将抛出IOError errno 13 (EACCES)

  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?我如何在这里检测案例(2)?

(My target platform is Windows) (我的目标平台是 Windows)

You can use os.access for checking your access permission.您可以使用os.access检查您的访问权限。 If access permissions are good, then it has to be the second case.如果访问权限很好,那么它必须是第二种情况。

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.从那里找出 errno 代码,你就准备好了。

As suggested in earlier comments, os.access does not return the correct result.正如之前评论中所建议的, os.access不会返回正确的结果。

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来自: 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM