Search code examples
pythonargparse

How can I automatically display the help on command line arguments error?


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

Solution

  • This thread over at Google groups has the following code snippet which seems to do the trick (modified slightly).

    class DefaultHelpParser(argparse.ArgumentParser):
        def error(self, message):
            sys.stderr.write('error: %s\n' % message)
            self.print_help()
            sys.exit(2)