Python optparse: what options got set?
While writing some code for EoC 2 to parse the command line, I needed
a generic way to find which command line options were set by the user.
That is, after I've parsed a command line, and have the return value
of the optparse.OptionParser.parse_args
method, how do I find which
options were set?
The return value is an instance of optparse.Values
, which does not have
a convenient method for that. So what I do is this:
classattrs = dir(optparse.Values)
for name in [_ for _ in dir(options) if _ not in classattrs]:
print name, getattr(options, name)
Slightly tricky, and it may stop working in a future version if they change things in the in (undocumented, therefore private) interface, but it's nice to be able to work around library design warts like this when the language itself is nicely powerful.