Getopts Value class and Template.Substitute not working (right away) working together
I have python code:
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 it gives me
AttributeError: Values instance has no attribute '__getitem__'
Because they options
are Values, not a dictionary.
How can I make this work?
(any other suggestions are appreciated, my pythonic sense is still cultivated ...)
a source to share
The following works for me:
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(vars(options)) #I'm assuming the uppercase S was a typo.
a source to share
OptionParser.parse_args
returns an object with option names as attributes, not as dictionary keys. The error options
you receive means it does not support signing, which would normally be done with __getitem__
.
So, in other words, your options are:
options.optiona
options.optionb
Instead
options['optiona']
options['optionb']
Template variable substitution assumes a dict
-like interface, so it tries to find optiona and optionb using the latter approach.
Use vars as RoadieRich
suggested in your answer to make the template substitution approach work. Also, if you really want an object Template
, I would recommend using a simple one print
:
print 'Option a is %s and option b is %s' % (options.optiona, options.optionb)
You can also combine the two approaches if you think parameters named string are better:
print 'Option a is %(optiona)s and option b is %(optionb)s' % vars(options)
a source to share