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

使用Gooey传递参数读取文件时出现Namespace类型错误问题问询

错误原因
  • 直接原因:GooeyParser.parse_args()返回的是存储所有参数的Namespace对象,你直接将这个对象赋值给filename传入open()函数,而open()只接受字符串、字节或者路径类对象,自然触发类型错误。
  • 潜在问题:你定义的全局变量pattern始终为空字符串,没有将第二个输入的搜索模式赋值给它,即便路径问题修复也无法完成搜索;全局变量foundDetector会导致多次运行程序时残留上一次的搜索结果。
修复方法

你需要从parse_args()返回的Namespace对象中取出对应参数的值,同时修正变量赋值逻辑,修改后的完整可运行代码如下:

import re
from gooey import Gooey, GooeyParser

# 火灾报警器探测器匹配规则
detectorPattern = re.compile(r'\d\d\.\d\d\d')

@Gooey
def main():
    parser = GooeyParser(description="火灾日志搜索工具")
    parser.add_argument(
        "Filename",
        help="选择待扫描的日志文件",
        widget="FileChooser"
    )
    parser.add_argument(
        "search_pattern",
        help="输入要搜索的匹配模式"
    )
    args = parser.parse_args()
    # 从Namespace对象中取出对应参数
    filename = args.Filename
    pattern = re.compile(args.search_pattern)
    foundDetector = []

    with open(filename, 'r', encoding='utf-8', errors='ignore') as reader:
        for line in reader:
            findLine = re.search(pattern, line)
            if findLine is not None:
                mo = detectorPattern.search(findLine.string)
                if mo: # 避免匹配不到探测器编号时报错
                    mog = mo.group()
                    if mog not in foundDetector:
                        foundDetector.append(mog)

    for x in foundDetector:
        print(x)

if __name__ == '__main__':
    main()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 16:27:04