我认为这是很难实现,包括一个很好的帮助消息,而只使用标准argparse函数。但是,您可以在解析参数后自行轻松地进行测试。你可以在结尾描述额外的需求。请注意,使用数字作为选项是不寻常的,我必须使用dest ='two',因为args.2不是有效的语法。
#!/usr/bin/env python
import argparse
parser = argparse.ArgumentParser(
description='bla bla',
epilog='Note: arguments -3 and -4 are required when -2 is missing')
parser.add_argument('-2', dest='two', action='store_true')
parser.add_argument('-3', dest='three')
parser.add_argument('-4', dest='four')
parser.add_argument('-5', dest='five')
args = parser.parse_args()
if not args.two and (args.three is None or args.four is None):
parser.error('arguments -3 and -4 are required when -2 is missing')
print 'Good:', args
有了这些结果:
[~]: ./test.py -h
usage: test.py [-h] [-2] [-3 THREE] [-4 FOUR] [-5 FIVE]
bla bla
optional arguments:
-h, --help show this help message and exit
-2
-3 THREE
-4 FOUR
-5 FIVE
Note: arguments -3 and -4 are required when -2 is missing
[~]: ./test.py -2
Good: Namespace(five=None, four=None, three=None, two=True)
[~]: ./test.py -3 a -4 b
Good: Namespace(five=None, four='b', three='a', two=False)
[~]: ./test.py -3 a
usage: test.py [-h] [-2] [-3 THREE] [-4 FOUR] [-5 FIVE]
test.py: error: arguments -3 and -4 are required when -2 is missing
[~]: ./test.py -2 -5 c
Good: Namespace(five='c', four=None, three=None, two=True)
[~]: ./test.py -2 -3 a
Good: Namespace(five=None, four=None, three='a', two=True)
使键安装在-2是复制其他命令可选一个子分析器。在顶层,将-3和-4链接在一起。 – Jiminion
使用以“-'开头的子分析器命令可能会非常棘手。 '-2'可能有效,但'-t'或'--two'不会因为它们看起来像可选项。但是,如果'-3'被定义为一个参数,那么'-2'不再作为子分析器命令(或选择)。 – hpaulj