您当前的位置:首页 > 计算机 > 编程开发 > Python

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

时间:12-14来源:作者:点击数:

参考 这里(link:https://stackoverflow.com/a/4042861/7152658) 。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))
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐