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

./myprogram -h

or:

./myprogram --help

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


当前回答

如果您的命令是用户需要选择某些操作的命令,则使用互斥组required=True。

这是对pd321给出的答案的扩展。

import argparse

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--batch", action='store', type=int,  metavar='pay_id')
group.add_argument("--list", action='store_true')
group.add_argument("--all", action='store_true', help='check all payments')

args=parser.parse_args()

if args.batch:
    print('batch {}'.format(args.batch))

if args.list:
    print('list')

if args.all:
    print('all')

输出:

$ python3 a_test.py 用法:a_test.py [h](——批pay_id | - |列表) A_test.py: error:参数之一——batch——list——all是必需的

这只是基本的帮助。其他的一些答案会给你充分的帮助。但至少你的用户知道他们可以做-h

其他回答

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

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

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

parser.print_help()
parser.exit()

解析器。Exit方法还接受一个状态(returncode)和一个消息值(包括一个尾随换行符自己!)。

举个固执己见的例子, :)

#!/usr/bin/env python3

""" Example argparser based python file
"""

import argparse

ARGP = argparse.ArgumentParser(
    description=__doc__,
    formatter_class=argparse.RawTextHelpFormatter,
)
ARGP.add_argument('--example', action='store_true', help='Example Argument')


def main(argp=None):
    if argp is None:
        argp = ARGP.parse_args()  # pragma: no cover

    if 'soemthing_went_wrong' and not argp.example:
        ARGP.print_help()
        ARGP.exit(status=64, message="\nSomething went wrong, --example condition was not set\n")


if __name__ == '__main__':
    main()  # pragma: no cover

示例调用:

$ python3 ~/helloworld.py; echo $?
usage: helloworld.py [-h] [--example]

 Example argparser based python file

optional arguments:
  -h, --help  show this help message and exit
  --example   Example Argument

Something went wrong, --example condition was not set
64
$ python3 ~/helloworld.py --example; echo $?
0

这种方法比大多数其他方法要优雅得多。与其重写error(),你可以通过包装parse_args()方法来更精确地控制行为:

import sys
import argparse


HelpFlags = ('help', '--help', '-h', '/h', '?', '/?', )


class ArgParser (argparse.ArgumentParser):
    
    def __init__(self, *args, **kws):
        super().__init__(*args, **kws)
    
    def parse_args(self, args=None, namespace=None):
        
        if args is None:
            args = sys.argv[1:]
        
        if len(args) < 1 or (args[0].lower() in HelpFlags):
            self.print_help(sys.stderr)
            sys.exit()
        
        return super().parse_args(args, namespace)

如果您的命令是用户需要选择某些操作的命令,则使用互斥组required=True。

这是对pd321给出的答案的扩展。

import argparse

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--batch", action='store', type=int,  metavar='pay_id')
group.add_argument("--list", action='store_true')
group.add_argument("--all", action='store_true', help='check all payments')

args=parser.parse_args()

if args.batch:
    print('batch {}'.format(args.batch))

if args.list:
    print('list')

if args.all:
    print('all')

输出:

$ python3 a_test.py 用法:a_test.py [h](——批pay_id | - |列表) A_test.py: error:参数之一——batch——list——all是必需的

这只是基本的帮助。其他的一些答案会给你充分的帮助。但至少你的用户知道他们可以做-h

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