在不带任何参数的情况下调用脚本时,显示带有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?
推荐答案
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()
打印到标准输出.作为
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屋!