Python how to get value from argparse from variable, but not the name of the variable?

ε祈祈猫儿з 提交于 2021-02-20 13:30:39

问题


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)

Can someone help me out?


回答1:


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)

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))

Or alternatively, getattr(args, svc_name).



来源:https://stackoverflow.com/questions/43624460/python-how-to-get-value-from-argparse-from-variable-but-not-the-name-of-the-var

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!