Python argparse - zhongjiajie/zhongjiajie.github.com GitHub Wiki
参考这里。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))