PyLint 在 shutil.rmtree(...) 的错误处理函数中引发 'misplaced-bare-raise'

PyLint raises 'misplaced-bare-raise' in error handler function for shutil.rmtree(...)

上下文: 我正在使用 shutil.rmtree(delDir, ignore_errors = False, onerror = readOnlyErrorHandler) 删除包含只读文件的目录树:

烦恼: PyLint(在 VS Code 中)将我的 readOnlyErrorHandler 函数中的 raise 命令标记为


问题:有没有办法在不对整个文件禁用 linting 的情况下获得此警告?

def readOnlyErrorHandler(func, path, exc_info):
  import errno
  if func in (os.rmdir, os.unlink, os.remove) and exc_info[1].errno == errno.EACCES:
    print (f"Retry '{func.__name__}' after chmod 0o777 on '{path}'")
    os.chmod(path, 0o777) 
    func(path)
  else:
    # marked as 'The raise statement is not inside an except clause' 
    # by pylint(misplaced-bare-raise)
    raise  # purpose: rethrow the other errors that brought me here

系统:Windows、Python3.6.3

测试:

from stat import S_IREAD, S_IRGRP, S_IROTH
import os
import shutil

path = "./some/path/to/files/"

# create read only files:
os.makedirs(path, exist_ok=True) 
for fn in ["one.txt","two.txt"]:
    filename = os.path.join(path, fn)
    with open(filename, "w") as f:
        f.write("read only")
    os.chmod(filename, S_IREAD|S_IRGRP|S_IROTH)

# try to delete files
# fails: shutil.rmtree(path)
# works
shutil.rmtree(path, ignore_errors=False, onerror=readOnlyErrorHandler)

您拥有 exc_info 中发生的异常的所有信息。在这种情况下 exc_info 将类似于

(
    <class 'FileNotFoundError'>, 
    FileNotFoundError(2, 'No such file or directory'), 
    <traceback object at 0x7fae2a66a0c8>
)

所以你可以 re-raise 例外

raise exc_info[1]

或自定义错误消息(但保留异常类型):

raise exc_info[0]("exception from readOnlyErrorHandler")