You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python日志清理脚本跨虚拟机运行报KeyError: 'Path'求助

问题原因分析与解决方案

这个KeyError: 'Path'的问题和模块、Python版本完全无关——两台机器环境一致,问题出在目标路径的文件结构差异上,具体原因如下:

核心问题点

你的PathToDict函数逻辑有明确的分支:

  • 当处理目录时,会添加'Path'、'Subdir'、'Num_Subdir'这些键;
  • 当处理文件时,只会设置'type': 'file',完全没有'Path'键。

而后续的dict函数默认dirs['Subdir']里的所有元素都是目录,直接访问dirs['Subdir'][elem]['Path']。第一台虚拟机的目标路径下的子项全是目录,所以运行正常;但第二台虚拟机的目标路径下混有文件,遍历到文件时就会因为找不到'Path'键抛出错误。

修复方案

你可以选择以下两种方式修复:

方案1:在dict函数中过滤文件

修改dict函数,只处理包含'Path'键的目录项:

def dict(path):
    dicto = {}
    for elem in dirs['Subdir']:
        sub_item = dirs['Subdir'][elem]
        # 仅处理目录(存在'Path'键的项)
        if 'Path' in sub_item:
            dicto[elem] = { sub_item['Path'] : sub_item['Num_Subdir'] }
    return dicto

方案2:在PathToDict中提前过滤文件

让Subdir只包含目录,从源头上避免文件进入后续逻辑:

def PathToDict(path):
    st = os.lstat(path)
    result = {}
    if S_ISDIR(st.st_mode):
        result['Path'] = path
        # 只遍历目录,过滤文件
        result['Subdir'] = { 
            name: PathToDict(os.path.join(path, name)) 
            for name in os.listdir(path)
            if S_ISDIR(os.lstat(os.path.join(path, name)).st_mode)
        }
        result['Num_Subdir'] = int(len([i for i, j, k in os.walk(path)]))
        # result['RealSize'] = subprocess.check_output(['du','-sh', path]).split()[0].decode('utf-8')
    else:
        result['type'] = 'file'
    return result

另外提个小建议:把dict函数改名吧,dict是Python内置类型的名称,作为自定义函数名会覆盖内置对象,可能引发其他潜在问题。

内容的提问来源于stack exchange,提问作者user6593995

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:28:17