本文介绍了Python argparse 条件要求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何设置argparse如下:
How do I set up argparse as follows:
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]
这里有很多类似的问题,但要么没有解决这种情况,要么我不明白.
There are a number of similar questions here, but either they don't address this situation or I don't understand.
Python 2.7 如果这很重要.
Python 2.7 if that matters.
推荐答案
子解析器(如评论中所建议)可能会起作用.
A subparser (as suggested in comments) might work.
另一种选择(因为 mutually_exclusive_group
不能完全做到这一点)只是手动编码,就像这样:
Another alternative (since mutually_exclusive_group
can't quite do this) is just to code it manually, as it were:
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
为此添加一个小驱动程序:
Adding a little driver to this:
import sys
sys.exit(main())
并运行您的示例,它似乎做对了;这里有两个运行:
and run with your examples, it seems to do the right thing; here are two runs:
$ 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
$
这篇关于Python argparse 条件要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!