Python如何从变量中获取argparse的值,而不是变量的名称? [英] Python how to get value from argparse from variable, but not the name of the variable?

查看:24
本文介绍了Python如何从变量中获取argparse的值,而不是变量的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我执行 args.svc_name,我期望等同于 args.option1,因为 svc_name 的值是 option1.但是我收到了'Namespace' 对象没有属性'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的值,而不是变量的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆