在没有任何参数的情况下调用脚本时,使用 python argparse 显示帮助消息 [英] Display help message with python argparse when script is called without any arguments
问题描述
这可能很简单.假设我有一个使用 argparse 来处理命令行参数/选项的程序.以下将打印帮助"消息:
This might be a simple one. Assume I have a program that uses argparse to process command line arguments/options. The following will print the 'help' message:
./myprogram -h
或:
./myprogram --help
但是,如果我在没有任何参数的情况下运行脚本,它不会做任何事情.我想要它做的是在没有参数的情况下调用它时显示使用消息.这是怎么做的?
But, if I run the script without any arguments whatsoever, it doesn't do anything. What I want it to do is to display the usage message when it is called with no arguments. How is that done?
推荐答案
这个答案来自 Steven Bethard 在 Google 网上论坛.我将其重新发布在这里是为了让没有 Google 帐户的人更容易访问.
This answer comes from Steven Bethard on Google groups. I'm reposting it here to make it easier for people without a Google account to access.
您可以覆盖 error
方法的默认行为:
You can override the default behavior of the error
method:
import argparse
import sys
class MyParser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write('error: %s\n' % message)
self.print_help()
sys.exit(2)
parser = MyParser()
parser.add_argument('foo', nargs='+')
args = parser.parse_args()
<小时>
请注意,每当 error
出现时,上述解决方案都会打印帮助消息方法被触发.例如, test.py --blah
将打印帮助信息如果 --blah
不是有效选项,也是如此.
Note that the above solution will print the help message whenever the error
method is triggered. For example, test.py --blah
will print the help message
too if --blah
isn't a valid option.
如果您想仅在没有提供参数的情况下打印帮助消息命令行,那么也许这仍然是最简单的方法:
If you want to print the help message only if no arguments are supplied on the command line, then perhaps this is still the easiest way:
import argparse
import sys
parser=argparse.ArgumentParser()
parser.add_argument('foo', nargs='+')
if len(sys.argv)==1:
parser.print_help(sys.stderr)
sys.exit(1)
args=parser.parse_args()
<小时>
请注意,parser.print_help()
默认打印到标准输出.如 init_js 建议,使用 parser.print_help(sys.stderr)
打印到 stderr.
Note that parser.print_help()
prints to stdout by default. As init_js suggests, use parser.print_help(sys.stderr)
to print to stderr.
这篇关于在没有任何参数的情况下调用脚本时,使用 python argparse 显示帮助消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!