【发布时间】:2015-11-02 05:20:20
【问题描述】:
有没有办法在argparse 中指定两个必需的参数,一个对应于子命令,另一个对应所有子命令。
我能做到的最接近的似乎是与
import argparse
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help='', dest='command', metavar='COMMAND', title='required arguments',
description='two arguments are required')
parser.add_argument('config', metavar='CONFIG', action='store', help='the config to use')
cmda_parser = subparsers.add_parser('cmdA', help='a first command')
cmdb_parser = subparsers.add_parser('cmdB', help='the second operation')
cmdc_parser = subparsers.add_parser('cmdC', help='yet another thing')
print(parser.parse_args())
给了
usage: enigma.py [-h] COMMAND ... CONFIG
positional arguments:
CONFIG the config to use
optional arguments:
-h, --help show this help message and exit
required arguments:
two arguments are required
COMMAND
cmdA a first command
cmdB the second operation
cmdC yet another thing
以及不显示CONFIG 的子命令的帮助;但我想要的是
usage: enigma.py [-h] COMMAND CONFIG
required arguments:
two arguments are required
COMMAND
cmdA a first command
cmdB the second operation
cmdC yet another thing
CONFIG the config to use
optional arguments:
-h, --help show this help message and exit
以及每个显示CONFIG 的子命令的帮助,例如。
usage: enigma.py cmdA CONFIG [-h]
required arguments:
CONFIG the config to use
optional arguments:
-h, --help show this help message and exit
有没有办法做到这一点?
我如何指定 两个 必需参数,其中一个是子命令,第二个“传播”到每个子命令作为必需参数?
【问题讨论】:
-
你试过先定义CONFIG吗?
-
@hpaulj:CONFIG 在 COMMAND 之后。
-
然后为每个子解析器定义它。
-
@hpaulj:问题的重点是看是否可以避免。
-
避免这种情况的目的是什么?它会使代码更清晰,还是更短?
argparse中没有“传播”机制。
标签: python python-2.7 argparse