Python argparse - zhongjiajie/zhongjiajie.github.com GitHub Wiki

Python-argparse

FAQ

不传参数或者参数传错的时候显示帮助文档

参考这里。argparse如果遇到空参数或者错误的参数处理的代码是

def error(self, message):
    """error(message: string)

    Prints a usage message incorporating the message to stderr and
    exits.

    If you override this in a subclass, it should not return -- it
    should either exit or raise an exception.
    """
    self.print_usage(_sys.stderr)
    args = {'prog': self.prog, 'message': message}
    self.exit(2, _('%(prog)s: error: %(message)s\n') % args)

由于self.print_usage只是subcommand的集合,所以提示比较少,如果重写error方法可以实现使用print_help方法展示更多的提示消息

def error(self, message):
    self.print_help()
    self.exit(2, '\n{} command error: {}, see help above.\n'.format(self.prog, message))

⚠️ **GitHub.com Fallback** ⚠️