python argparse: How can I display help automatically on error?

Viewed 20386

Currently when I enter invalid options or omit positional arguments, argparse kicks me back to the prompt and displays the usage for my app. This is ok, but I would rather automatically display the full help listing (that explains the options, etc) than require the user to type

./myscript.py -h

Thanks!

Jamie

5 Answers

I just fixed this same problem myself using the following syntax:

parser = ArgumentParser()
... add arguments ...
parser.usage = parser.format_help()
args = parser.parse_args()

Suppress printing of usage with usage=argparse.SUPPRESS. Then catch the SystemExit exception that ArgumentParser raises on error, print the help, and exit by raising the exception again.

parser = argparse.ArgumentParser(usage=argparse.SUPPRESS)
parser.add_argument(...)
try:
    args = parser.parse_args()
except SystemExit:
    parser.print_help()
    raise

You, also, can print help without using a class or exception:

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(...)
    ...

. Just wrap ArgumentParser.error function in your and intercept message argument. I answered, there, earlier:

https://stackoverflow.com/a/60714163/10152015

Related