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

半腔热情 提交于 2019-12-03 09:51:23

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!