我认为仅使用标准的 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)