如何设置 argparse 如下:
if -2 is on the command line, no other arguments are required
if -2 is not on the command line, -3 and -4 arguments are required
例如,
-2 [good]
-3 a -4 b [good]
-3 a [not good, -4 required]
-2 -5 c [good]
-2 -3 a [good]
这里有很多类似的问题,但要么它们没有解决这种情况,要么我不明白。
Python 2.7(如果有的话)。
子解析器(如评论中建议的)可能会起作用。
另一种选择(因为mutually_exclusive_group
不能完全做到这一点)只是手动编码,如下所示:
import argparse
def main():
parser = argparse.ArgumentParser()
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:
if args.three is None or args.four is None:
parser.error('without -2, *both* -3 <a> *and* -4 <b> are required')
print args
return 0
添加一个小驱动程序:
import sys
sys.exit(main())
并用你的例子来运行,它似乎做了正确的事情;这是两次运行:
$ python mxgroup.py -2; echo $?
Namespace(five=None, four=None, three=None, two=True)
0
$ python mxgroup.py -3 a; echo $?
usage: mxgroup.py [-h] [-2] [-3 THREE] [-4 FOUR] [-5 FIVE]
mxgroup.py: error: without -2, *both* -3 <a> *and* -4 <b> are required
2
$
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)