更好地帮助 argparse 子命令

Better help for argparse subcommands

给定以下代码片段:

import argparse
import sys

parser = argparse.ArgumentParser()

subparsers = parser.add_subparsers(help="subcommand help")

command1 = subparsers.add_parser("foo", description="Run foo subcommand")
command2 = subparsers.add_parser("bar", description="Run bar subcommand")
opts = parser.parse_args(sys.argv[1:])

当我为此打印帮助时,我得到了这个:

usage: test.py [-h] {foo,bar} ...

positional arguments:
  {foo,bar}   subcommand help

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

有没有办法让它打印这样的东西:

usage: test.py [-h] {foo,bar} ...

subcommands:
  foo         Run foo subcommand
  bar         Run bar subcommand

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

不提供自定义格式化程序?如果我更改格式化程序,那么它也会更改有关如何打印帮助的所有其他内容,但在我的情况下,我只想更改从父(子)命令打印子命令帮助的方式。

您需要设置 help parameter, not the description parameter,以获得您想要的输出:

import argparse
import sys

parser = argparse.ArgumentParser()

subparsers = parser.add_subparsers(help="subcommand help")

command1 = subparsers.add_parser("foo", help="Run foo subcommand")
command2 = subparsers.add_parser("bar", help="Run bar subcommand")
opts = parser.parse_args(sys.argv[1:])

输出:

usage: test.py [-h] {foo,bar} ...

positional arguments:
  {foo,bar}   subcommand help
    foo       Run foo subcommand
    bar       Run bar subcommand

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

argparse 文档对帮助值有这样的说法:

The help value is a string containing a brief description of the argument. When a user requests help (usually by using -h or --help at the command line), these help descriptions will be displayed with each argument.

这就是关于描述值:

This argument gives a brief description of what the program does and how it works. In help messages, the description is displayed between the command-line usage string and the help messages for the various arguments.