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

为什么使用argparse时出现TypeError: 'Namespace' object is not subscriptable错误

argparse使用报错解决方案:TypeError: 'Namespace' object is not subscriptable

核心报错原因

argparse.ArgumentParser.parse_args()返回的是Namespace对象,不支持字典式的下标取值逻辑,你代码里args["encodings"]的写法不符合该对象的访问规则。
同时你代码还存在一处隐藏错误:你实例化的参数解析器命名为ap,但调用解析方法时用了未定义的parser变量,运行时也会抛出变量未定义报错。

修正后可运行代码

import argparse
import pickle

ap = argparse.ArgumentParser()
ap.add_argument("-e", "--encodings", required=True,
                help="path to serialized db of facial encodings")
ap.add_argument("-i", "--image", required=True,
                help="path to input image")
ap.add_argument("-d", "--detection-method", type=str, default="cnn",
                help="face detection model to use: either `hog` or `cnn`")
ap.add_argument("-fnn", "--fast-nn", action="store_true")
# 修正点1:使用正确的解析器对象名ap,无额外参数时会自动读取命令行传入的参数
args = ap.parse_args()
print(args)

# load the known faces and embeddings
print("[INFO] loading encodings...")
# 修正点2:Namespace对象用.访问对应属性,不要用[]下标取值
data = pickle.loads(open(args.encodings, "rb").read())

补充调试说明

  • 本地调试不想每次从命令行传参数的话,可以给add_argument方法补充default参数,比如给--encodings加default="./encodings.pickle"就能直接读取你本地已准备好的文件,同时把ap.parse_args()改成ap.parse_args([])即可跳过命令行参数校验
  • 如果你确实需要用字典的方式访问参数,可以调用vars(args)把Namespace对象转为字典,转换后就可以用args_dict["encodings"]的写法取值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 06:06:06