Python argparse 组混淆

Python argparse groups confusion

我想创建一个 "installer" 程序,您可以这样调用:

installer install PROGRAM
installer install PROGRAM MY_DIR
installer list

我正在尝试指示 argparse,以便您必须 使用 installlist 调用安装程序。 list 不需要参数,而 install 需要要安装的程序和可选的目标目录。这是我目前所拥有的:

import argparse

parser = argparse.ArgumentParser(prog="installer")
parser.add_argument('action', choices=['install', 'list'], help='install|list', type=str)

subparsers = parser.add_subparsers()

install_group = subparsers.add_parser('install', help='install program')
install_group.add_argument('program_name',    help='name of the program to install', type=str)
install_group.add_argument('destination_dir', help='where to install the program', nargs='?', type=str)

list_group = subparsers.add_parser('list', help="list available programs")

args   = parser.parse_args()

问题是生成的帮助似乎没有反映这一点:

# python installer.py --help

usage: installer [-h] {install,list} {install,list} ...

positional arguments:
  {install,list}  install|list
  {install,list}
    install       install program
    list          list available programs

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

python installer.py install --help的帮助也是一样的。没有提到 destination_dir 或 program_name

有什么帮助吗?

action 的论点令人困惑 argparse。删除那条线;您只需要两个 subparsers 即可使 CLI 正常运行(包括拒绝 installlist 以外的任何内容)。

全局帮助:

C:\Python34>python installer.py --help
usage: installer [-h] {install,list} ...

positional arguments:
  {install,list}
    install       install program
    list          list available programs

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

安装帮助:

C:\Python34>python installer.py install --help
usage: installer install [-h] program_name [destination_dir]

positional arguments:
  program_name     name of the program to install
  destination_dir  where to install the program

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

不支持的参数:

C:\Python34>python installer.py hello
usage: installer [-h] {install,list} ...
installer: error: invalid choice: 'hello' (choose from 'install', 'list')

请注意,您可以通过将接受的值之一传递给action 然后,仍然可以获得子解析器的帮助命名子解析器:

C:\Python34>python installer.py install install --help
usage: installer {install,list} install [-h] program_name [destination_dir]

positional arguments:
  program_name     name of the program to install
  destination_dir  where to install the program

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