假设我有一个使用argparse处理命令行参数/选项的程序。下面将打印“帮助”信息:

./myprogram -h

or:

./myprogram --help

但是,如果我不带任何参数运行脚本,它什么都不会做。我想要它做的是在不带参数地调用它时显示用法消息。怎么做呢?


当前回答

用nargs设置位置参数,检查位置参数是否为空。

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?')
args = parser.parse_args()
if not args.file:
    parser.print_help()

参考Python nargs

其他回答

用nargs设置位置参数,检查位置参数是否为空。

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?')
args = parser.parse_args()
if not args.file:
    parser.print_help()

参考Python nargs

可以使用try/except来代替编写类

try:
    options = parser.parse_args()
except:
    parser.print_help()
    sys.exit(0)

好处是工作流更加清晰,并且不需要存根类。缺点是第一个“usage”行打印了两次。

这至少需要一个强制参数。如果没有强制参数,在命令行上提供零参数是有效的。

把我的版本扔到这里:

import argparse

parser = argparse.ArgumentParser()
args = parser.parse_args()
if not vars(args):
    parser.print_help()
    parser.exit(1)

您可能会注意到解析器。exit -我这样做主要是因为它保存了一个导入行,如果这是文件中sys的唯一原因…

这里的大多数答案都需要导入另一个模块,比如sys,或者使用可选参数。我想找到一个只使用argparse的答案,使用所需的参数,如果可能的话,不捕获异常。最后我得到了以下结论:

import argparse

if __name__ == '__main__':

    arg_parser = argparse.ArgumentParser(add_help=False)
    arg_parser.add_argument('input_file', type=str, help='The path to the input file.')
    arg_parser.add_argument('output_file', type=str, help='The path to the output file.')
    arg_parser.add_argument('-h','--help', action='store_true', help='show this help message and exit')
    arg_parser.usage = arg_parser.format_help()
    args = arg_parser.parse_args()

The main idea was to use the format_help function in order to provide the help string to the usage statement. Setting add_help to False in the call to ArgumentParser() prevents the help statement from printing twice in certain circumstances. However, I had to create an argument for the optional help argument that mimicked the typical help message once it was set to False in order to display the optional help argument in the help message. The action is set to store_true in the help argument to prevent the help message from filling in a value like HELP for the parameter when it prints the help message.

最简洁的解决方案是手动传递默认参数,如果没有在命令行中给出:

parser.parse_args(args=None if sys.argv[1:] else ['--help'])

完整的例子:

import argparse, sys

parser = argparse.ArgumentParser()
parser.add_argument('--host', default='localhost', help='Host to connect to')
# parse arguments
args = parser.parse_args(args=None if sys.argv[1:] else ['--help'])

# use your args
print("connecting to {}".format(args.host))

如果调用w/o参数,这将打印完整的帮助(而不是简短的用法)。