Python argparse条件要求

foo*_*ion 15 python python-2.7 argparse

如何设置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
Run Code Online (Sandbox Code Playgroud)

例如,

-2 [good]
-3 a -4 b [good]
-3 a [not good, -4 required]
-2 -5 c [good]
-2 -3 a [good]
Run Code Online (Sandbox Code Playgroud)

这里有许多类似的问题,但要么他们没有解决这种情况,要么我不理解.

Python 2.7如果重要的话.

tor*_*rek 14

subparser(如评论中所示)可能有效.

另一种选择(因为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
Run Code Online (Sandbox Code Playgroud)

添加一个小驱动程序:

import sys
sys.exit(main())
Run Code Online (Sandbox Code Playgroud)

和你的例子一起运行,似乎做对了; 这是两个运行:

$ 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
$ 
Run Code Online (Sandbox Code Playgroud)