This isn't good (also, because intercepts all errors), but:
def _error(parser):
def wrapper(interceptor):
parser.print_help()
sys.exit(-1)
return wrapper
def _args_get(args=sys.argv[1:]):
parser = argparser.ArgumentParser()
parser.error = _error(parser)
parser.add_argument(...)
...
Here is definition of the error
function of the ArgumentParser
class:
https://github.com/python/cpython/blob/276eb67c29d05a93fbc22eea5470282e73700d20/Lib/argparse.py#L2374
. As you see, following signature, it takes two arguments. However, functions outside the class nothing knows about first argument: self
, because, roughly speaking, this is parameter for the class. (I know, that you know...) Thereby, just pass own self
and message
in _error(...)
can't (
def _error(self, message):
self.print_help()
sys.exit(-1)
def _args_get(args=sys.argv[1:]):
parser = argparser.ArgumentParser()
parser.error = _error
...
...
will output:
...
"AttributeError: 'str' object has no attribute 'print_help'"
). You can pass parser
(self
) in _error
function, by calling it:
def _error(self, message):
self.print_help()
sys.exit(-1)
def _args_get(args=sys.argv[1:]):
parser = argparser.ArgumentParser()
parser.error = _error(parser)
...
...
, but you don't want exit the program, right now. Then return it:
def _error(parser):
def wrapper():
parser.print_help()
sys.exit(-1)
return wrapper
...
. Nonetheless, parser
doesn't know, that it has been modified, thus when an error occurs, it will send cause of it (by the way, its localized translation). Well, then intercept it:
def _error(parser):
def wrapper(interceptor):
parser.print_help()
sys.exit(-1)
return wrapper
...
. Now, when error occurs and parser
will send cause of it, you'll intercept it, look at this, and... throw out.