问题描述
如果我执行args.svc_name,则期望与args.option1等效,因为svc_name的值为option1.但是我收到名称空间"对象没有属性"svc_name's"的错误
If I do args.svc_name, I was expecting equivalent to args.option1, because the svc_name's value is option1. But i got error for "'Namespace' object has no attribute 'svc_name's'"
parser = argparse.ArgumentParser(prog=None,description="test")
parser.add_argument("--option1", nargs="?",help="option")
args = parser.parse_args()
svc_name = "option1"
print (args.svc_name)
有人可以帮我吗?
推荐答案
ArgumentParser
类将键公开为直接属性,而不是映射,因此直接获得该属性可以直接访问它.根据问题中的示例,它就是
The ArgumentParser
class exposes the keys as direct attributes rather than a mapping, so to get the attribute directly one would simply access it directly. As per the example from the question, it would simply be
print(args.option1)
如果希望使用其他变量(例如问题中的 svc_name
)存储属性/标志以从argparser获取值,只需将其转换为映射即可(例如dict
),先使用 vars
调用get方法
If one wish to have some other variable (e.g. svc_name
from the question) to store the attribute/flag to acquire the value from the argparser, simply turn it into a mapping (i.e. dict
) using vars
and then call the get method
print(vars(args).get(svc_name))
或者,或者, getattr(args,svc_name)
.
这篇关于Python如何从变量中的argparse获取值,而不是变量的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!