getopts Values 类和 Template.Substitute 不能(立即)一起工作
我有类似的 python 代码:
from string import Template
import optparse
def main():
usage = "usage: %prog options outputname"
p = optparse.OptionParser(usage)
p.add_option('--optiona', '-a', default="")
p.add_option('--optionb', '-b', default="")
options, arguments = p.parse_args()
t = Template('Option a is ${optiona} option b is ${optionb}')
print t.substitute(options)
但这给了我
AttributeError: Values instance has no attribute '__getitem__'
因为 options
是一个值而不是字典。
我如何巧妙地完成这项工作?
(欢迎任何其他建议,我的Python意识仍在培养中......)
I have python code something like:
from string import Template
import optparse
def main():
usage = "usage: %prog options outputname"
p = optparse.OptionParser(usage)
p.add_option('--optiona', '-a', default="")
p.add_option('--optionb', '-b', default="")
options, arguments = p.parse_args()
t = Template('Option a is ${optiona} option b is ${optionb}')
print t.substitute(options)
But that gives me
AttributeError: Values instance has no attribute '__getitem__'
Because options
is a Values and not a dictionary.
How do I neatly make this work?
(any other suggestions welcome, my pythonic sense is still being nurtured...)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
OptionParser.parse_args 返回一个对象,其中选项变量名称作为属性,而不是字典键。 您收到的错误意味着
options
不支持下标,通常通过实现__getitem__
来实现。因此,换句话说,您的选项位于:
而不是:
模板变量替换需要一个类似于 dict 的接口,因此它尝试使用后一种方法来查找 optiona 和 optionb。
按照
RoadieRich
在他的回答中建议的方式使用 vars 来使模板替换方法发挥作用。 或者,除非您确实需要Template
对象,否则我建议使用简单的print
:如果您认为命名字符串参数更好,您也可以结合使用这两种方法:
OptionParser.parse_args
returns an object with the option variable names as attributes, rather than as dictionary keys. The error you're getting means thatoptions
does not support subscripting, which it would normally do by implementing__getitem__
.So, in other words, your options are at:
Rather than:
Template variable substitution expects a
dict
-like interface, so it's trying to find optiona and optionb using the latter approach.Use vars as
RoadieRich
suggests in his answer to make the template substitution approach work. Alternatively, unless you really need aTemplate
object, I'd recommend using a simpleprint
:You can also combine the two approaches if you feel that named string parameters are better:
以下似乎对我有用:
The following appears to work for me: