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.
This is
pass_through.py
example from Optik distribution.Python 2.7 (which didn't exist when this question was asked) now provides the argparse module. You may be able to use
ArgumentParser.parse_known_args()
to accomplish the goal of this question.Here's one way to have unknown arguments added to the result
args
ofOptionParser.parse_args
, with a simple subclass.And here's a snippet to show that it works:
By default there is no way to modify the behavior of the call to
error()
that is raised when an undefined option is passed. From the documentation at the bottom of the section on how optparse handles errors:The simplest example of this would be:
This would simply make all calls to
error()
do nothing. Of course this isn't ideal, but I believe that this illustrates what you'd need to do. Keep in mind the docstring fromerror()
and you should be good to go as you proceed: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
: