Question

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

Was it helpful?

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)

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top