参考 这里(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))
