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

./myprogram -h

or:

./myprogram --help

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


当前回答

这并不好(因为会拦截所有错误),但是:

def _error(parser):
    def wrapper(interceptor):
        parser.print_help()

        sys.exit(-1)

    return wrapper

def _args_get(args=sys.argv[1:]):
    parser = argparser.ArgumentParser()

    parser.error = _error(parser)

    parser.add_argument(...)
    ...

下面是ArgumentParser类的错误函数的定义。

如您所见,下面的签名有两个参数。然而,类之外的函数对第一个参数self一无所知,因为粗略地说,这个参数是类的。

def _error(self, message):
    self.print_help()

    sys.exit(-1)

def _args_get(args=sys.argv[1:]):
    parser = argparser.ArgumentParser()

    parser.error = _error
    ...

将输出:

"AttributeError: 'str' object has no attribute 'print_help'"

你可以在_error函数中传递parser (self),通过调用它:

def _error(self, message):
    self.print_help()

    sys.exit(-1)

def _args_get(args=sys.argv[1:]):
    parser = argparser.ArgumentParser()

    parser.error = _error(parser)
    ...

但是如果你现在不想退出程序,返回它:

def _error(parser):
    def wrapper():
        parser.print_help()

        sys.exit(-1)

    return wrapper

尽管如此,解析器并不知道它已被修改。因此,当发生错误时,它将打印错误的原因(顺便说一下,这是一个本地化的翻译)。所以截取它:

def _error(parser):
    def wrapper(interceptor):
        parser.print_help()

        sys.exit(-1)

    return wrapper

现在,当发生错误时,解析器将打印错误的原因,您将拦截它,查看它,然后……扔掉。

其他回答

这是一个很简单的答案。大多数时候使用argparse是为了检查是否设置了形参,以便调用函数来执行某些操作。

如果没有参数,则在最后输出else并打印帮助。简单而有效。

import argparse
import sys
parser = argparse.ArgumentParser()

group = parser.add_mutually_exclusive_group()
group.add_argument("--holidays", action='store_true')
group.add_argument("--people", action='store_true')

args=parser.parse_args()
if args.holidays:
    get_holidays()
elif args.people:
    get_people()
else:
    parser.print_help(sys.stderr)

把我的版本扔到这里:

import argparse

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

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

对于argparse,你可以使用ArgumentParser.print_usage():

parser.argparse.ArgumentParser()
# parser.add_args here

# sys.argv includes a list of elements starting with the program
if len(sys.argv) < 2:
    parser.print_usage()
    sys.exit(1)

打印帮助 ArgumentParser.print_usage(文件=没有) 打印关于如何在命令行上调用ArgumentParser的简要描述。如果file为None,则sys。假设是Stdout。

这里的大多数答案都需要导入另一个模块,比如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.

如果你必须为脚本运行指定参数,使用ArgumentParser所需的参数,如下所示

parser.add_argument('--foo', required=True)

如果脚本在没有任何参数的情况下运行,Parse_args()将报告错误。