cycling through options

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Mar 17 01:02:38 CET 2010


En Tue, 16 Mar 2010 11:30:51 -0300, Dieter Faulbaum  
<Dieter.Faulbaum at bessy.de> escribió:

> is there a better way for cycling through all options than this:
>
>
> (options, args) = parser.parse_args()
> for opt in options.__dict__.keys():
>      print opt, ":", options.__dict__[opt]

(I assume parser is an optparse.OptionParser instance)
You may rewrite it as:

for oname, ovalue in vars(options).iteritems():
   print oname, ":", ovalue

This assumes that the only instance attributes existing in 'options' are,  
uh, parsed options from the command line. I could not find such guarantee  
in the documentation. Another way would be to ask the parser about the  
options it knows of:

for oname in (o.dest for o in parser.option_list if o.dest):
   print oname, ":", getattr(options, oname, None)

-- 
Gabriel Genellina




More information about the Python-list mailing list