pythonoptparse

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


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' ]

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.


Solution

  • Per synack's request in a different answer's comments, I'm posting my hack of a solution which sanitizes the inputs before passing them to the parent OptionParser:

    import optparse
    import re
    import copy
    import SCons
    
    class NoErrOptionParser(optparse.OptionParser):
        def __init__(self,*args,**kwargs):
            self.valid_args_cre_list = []
            optparse.OptionParser.__init__(self, *args, **kwargs)
    
        def error(self,msg):
            pass
    
        def add_option(self,*args,**kwargs):
            self.valid_args_cre_list.append(re.compile('^'+args[0]+'='))
            optparse.OptionParser.add_option(self, *args, **kwargs)
    
        def parse_args(self,*args,**kwargs):
            # filter out invalid options
            args_to_parse = args[0]
            new_args_to_parse = []
            for a in args_to_parse:
                for cre in self.valid_args_cre_list:
                    if cre.match(a):
                        new_args_to_parse.append(a)
    
    
            # nuke old values and insert the new
            while len(args_to_parse) > 0:
                args_to_parse.pop()
            for a in new_args_to_parse:
                args_to_parse.append(a)
    
            return optparse.OptionParser.parse_args(self,*args,**kwargs)
    
    
    def AddOption_and_get_NoErrOptionParser( *args, **kwargs):
        apply( SCons.Script.AddOption, args, kwargs)
        no_err_optparser = NoErrOptionParser(optparse.SUPPRESS_USAGE)
        apply(no_err_optparser.add_option, args, kwargs)
    
        return no_err_optpars