Python optparse 值实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1753460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:59:51  来源:igfitidea点击:

Python optparse Values Instance

pythondictionaryoptparse

提问by mgag

How can I take the opt result of

我怎样才能得到选择结果

opt, args = parser.parse_args()

and place it in a dict? Python calls opt a "Values Instance" and I can't find any way to turn a Values Instance into a list or dict. One can't copy items from opt in this way,

并将其放在字典中?Python 调用选择“值实例”,我找不到任何方法将值实例转换为列表或字典。不能以这种方式从 opt 复制项目,

for i in opt:
 myDict[i] = opt[i]

instead, its a clumsy,

相反,它很笨拙,

myDict[parm1] = opt.parm1
myDict[parm2] = opt.parm2

which implies that every time I add an option, I have to update this code as well; there should be a way to let this take care of itself.

这意味着每次添加选项时,我也必须更新此代码;应该有办法让它自行解决。

回答by bcat

options, args = parser.parse_args()
option_dict = vars(options)

(Source is this python-ideas post.)

(来源是这个 python-ideas 帖子。)