python argparse:如何在出现错误时自动显示帮助? [英] python argparse: How can I display help automatically on error?

查看:57
本文介绍了python argparse:如何在出现错误时自动显示帮助?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,当我输入无效的选项或省略位置参数时,argparse将我踢回提示并显示我的应用程序的用法.可以,但是我宁愿自动显示完整的帮助列表(解释选项等),而不要求用户键入

Currently when I enter invalid options or omit positional arguments, argparse kicks me back to the prompt and displays the usage for my app. This is ok, but I would rather automatically display the full help listing (that explains the options, etc) than require the user to type

./myscript.py -h

谢谢!

杰米

推荐答案

线程具有以下代码段,似乎可以解决问题(略有修改).

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)

这篇关于python argparse:如何在出现错误时自动显示帮助?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆