Python argparse组混淆

时间:2015-04-14 13:20:48

标签: python argparse

我想创建一个"安装程序"你可以这样调用的程序:

installer install PROGRAM
installer install PROGRAM MY_DIR
installer list

我试图指示argparse,以便必须使用installlist来调用安装程序。 list不需要参数,而安装需要安装程序和目标目录。这就是我到目前为止所做的:

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

任何帮助?

1 个答案:

答案 0 :(得分:3)

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')

请注意,可以仍然获得subparser帮助,方法是将其中一个可接受的值传递给action ,然后命名一个subparser:

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