python argparse:如何在出错时自动显示帮助? [英] python argparse: How can I display help automatically on error?
本文介绍了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
谢谢!
杰米
推荐答案
这个 thread 在 Google 组上有以下代码片段,它似乎可以解决问题(稍作修改).
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屋!
查看全文