为什么我会收到这个错误:TypeError: 'Namespace' object is not subscriptable?

12

我正在使用argparse库遇到问题。

我有encodings.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")
args = parser.parse_args('')
print(args)

# load the known faces and embeddings
print("[INFO] loading encodings...")
data = pickle.loads(open(args["encodings"], "rb").read())

源代码可以在这里找到。

1个回答

7
你会看到这个错误,是因为parse_args()方法返回一个包含解析后参数的命名空间(Namespace)。
当打印该方法的结果时,你将看到创建的命名空间:Namespace(encodings='encoding', image='image', detection_method='cnn', fast_nn=False) 为了访问参数,应该使用点符号表示法(例如args.encodingsargs.image)。
修改后的代码:
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")
args = parser.parse_args()
print(args)

# load the known faces and embeddings
print("[INFO] loading encodings...")
data = pickle.loads(open(args.encodings, "rb").read())

仍然面临相同的错误。 您能否通过修改上述代码进行澄清?我担心我可能错过了某些东西。 - Ahmed Abousari
更正 @AhmedAbousari。 - H. Ross
解析器未定义,因此我执行了以下操作: parser = argparse.ArgumentParser() args = parser.parse_args() 发生异常,请使用%tb查看完整的回溯。 SystemExit:2 - Ahmed Abousari
当我将代码修改为: args = parser.parse_args('') 我遇到了以下错误: 属性错误:'Namespace'对象没有属性'encodings' 但是如果我像您的代码一样不使用 (''): args = parser.parse_args() 我遇到了以下错误: 发生异常,请使用%tb查看完整的跟踪。 SystemExit: 2 - Ahmed Abousari
当在IPython中调用parse_args时,出现SystemExit(2)错误。 - H. Ross

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接