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:
If optparse‘s default error-handling behaviour does not suit your needs, you’ll need to subclass OptionParser and override its exit() and/or error() methods.
The simplest example of this would be:
class MyOptionParser(OptionParser):
def error(self, msg):
pass
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 from error()
and you should be good to go as you proceed:
Print a usage message incorporating 'msg' to stderr and exit. If you override this in a subclass, it should not return -- it should either exit or raise an exception.