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

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)

To print help you might want to use: print_help function on ArgumentParser instance

parser = argparse.ArgumentParser()
(...)
parser.print_help()

To print help message on error you need to create own subclass of ArgumentParser instance, that overrides error() method. For example like that:

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

When this parser encounters unparseable argument line it will print help.


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