簡體   English   中英

Python:檢查文件是否已鎖定

[英]Python : Check file is locked

我的目標是知道文件是否被另一個進程鎖定,即使我無權訪問該文件!

為了更清楚,假設我使用帶有'wb'開關(用於寫入)的python 內置open()文件。 open()將拋出IOError errno 13 (EACCES)

  1. 用戶無權訪問該文件或
  2. 該文件被另一個進程鎖定

我如何在這里檢測案例(2)?

(我的目標平台是 Windows)

您可以使用os.access檢查您的訪問權限。 如果訪問權限很好,那么它必須是第二種情況。

根據文檔:

errno.EACCES
    Permission denied
errno.EBUSY

    Device or resource busy

所以只需這樣做:

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

從那里找出 errno 代碼,你就准備好了。

正如之前評論中所建議的, 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM