Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get optparse's OptionParser to ignore invalid options?

Tags:

In python's OptionParser, how can I instruct it to ignore undefined options supplied to method parse_args?

e.g.
I've only defined option --foo for my OptionParser instance, but I call parse_args with list
[ '--foo', '--bar' ]

EDIT:
I don't care if it filters them out of the original list. I just want undefined options ignored.

The reason I'm doing this is because I'm using SCons' AddOption interface to add custom build options. However, some of those options guide the declaration of the targets. Thus I need to parse them out of sys.argv at different points in the script without having access to all the options. In the end, the top level Scons OptionParser will catch all the undefined options in the command line.

like image 456
Ross Rogers Avatar asked Dec 11 '09 00:12

Ross Rogers


1 Answers

Here's one way to have unknown arguments added to the result args of OptionParser.parse_args, with a simple subclass.

from optparse import (OptionParser,BadOptionError,AmbiguousOptionError)  class PassThroughOptionParser(OptionParser):     """     An unknown option pass-through implementation of OptionParser.      When unknown arguments are encountered, bundle with largs and try again,     until rargs is depleted.        sys.exit(status) will still be called if a known argument is passed     incorrectly (e.g. missing arguments or bad argument types, etc.)             """     def _process_args(self, largs, rargs, values):         while rargs:             try:                 OptionParser._process_args(self,largs,rargs,values)             except (BadOptionError,AmbiguousOptionError), e:                 largs.append(e.opt_str) 

And here's a snippet to show that it works:

# Show that the pass-through option parser works. if __name__ == "__main__": #pragma: no cover     parser = PassThroughOptionParser()     parser.add_option('-k', '--known-arg',dest='known_arg',nargs=1, type='int')     (options,args) = parser.parse_args(['--shazbot','--known-arg=1'])         assert args[0] == '--shazbot'     assert options.known_arg == 1      (options,args) = parser.parse_args(['--k','4','--batman-and-robin'])     assert args[0] == '--batman-and-robin'     assert options.known_arg == 4 
like image 158
justind Avatar answered Sep 21 '22 20:09

justind