Python argparse:具有必需选项的互斥必需组

Python argparse:具有必需选项的互斥必需组,python,python-2.7,argparse,Python,Python 2.7,Argparse,我正在尝试使用一个必需的参数创建一个必需的互斥组。下面是我写的代码 #!/usr/bin/python import argparse import sys # Check for the option provided as part of arguments def parseArgv(): parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() group.

我正在尝试使用一个必需的参数创建一个必需的互斥组。下面是我写的代码

#!/usr/bin/python

import argparse
import sys

# Check for the option provided as part of arguments
def parseArgv():
    parser = argparse.ArgumentParser()
    group = parser.add_mutually_exclusive_group()
    group.add_argument("-v", "--verbose", choices=[1,2,3,4],
            help = "Increase verbosity")
    group.add_argument("-q", "--quiet", action="store_true", help = "Run quietly")
    name = parser.add_mutually_exclusive_group(required=True)
    name.add_argument("-n", "--name", help = "Name of the virtual machine")
    name.add_argument("-t", "--template", help = "Name of the template to use \
            for creating vm. If path is not provided then it will be looked \
            under template directory.")
    parser.add_argument("-s", "--save", help = "Save the machine template. If \
            path is not provided then it will be saved under template directory.");
    #parser.add_argument("-k", "--kick_start", required = True, help = "Name of the \
    #        kick start file. If path is not provided then it will be look into http \
    #        directory.")
    if len(sys.argv) == 1:
        parser.print_help()
    args = parser.parse_args()

if __name__ == '__main__':
    parseArgv()
现在这个程序的输出如下

$ python test.py 
usage: test.py [-h] [-v {1,2,3,4} | -q] (-n NAME | -t TEMPLATE) [-s SAVE]

optional arguments:
  -h, --help            show this help message and exit
  -v {1,2,3,4}, --verbose {1,2,3,4}
                        Increase verbosity
  -q, --quiet           Run quietly
  -n NAME, --name NAME  Name of the virtual machine
  -t TEMPLATE, --template TEMPLATE
                        Name of the template to use for creating vm. If path
                        is not provided then it will be looked under template
                        directory.
  -s SAVE, --save SAVE  Save the machine template. If path is not provided
                        then it will be saved under template directory.
usage: test.py [-h] [-v {1,2,3,4} | -q] (-n NAME | -t TEMPLATE) [-s SAVE]
test.py: error: one of the arguments -n/--name -t/--template is required
但是如果我取消对第20-22行的注释,那么输出的变化如下

$ python test.py 
usage: test.py [-h] [-v {1,2,3,4} | -q] (-n NAME | -t TEMPLATE) [-s SAVE] -k
               KICK_START

optional arguments:
  -h, --help            show this help message and exit
  -v {1,2,3,4}, --verbose {1,2,3,4}
                        Increase verbosity
  -q, --quiet           Run quietly
  -n NAME, --name NAME  Name of the virtual machine
  -t TEMPLATE, --template TEMPLATE
                        Name of the template to use for creating vm. If path
                        is not provided then it will be looked under template
                        directory.
  -s SAVE, --save SAVE  Save the machine template. If path is not provided
                        then it will be saved under template directory.
  -k KICK_START, --kick_start KICK_START
                        Name of the kick start file. If path is not provided
                        then it will be look into http directory.
usage: test.py [-h] [-v {1,2,3,4} | -q] (-n NAME | -t TEMPLATE) [-s SAVE] -k
               KICK_START
test.py: error: argument -k/--kick_start is required

但是我希望-n/-t和-k都是必须的。如何达到同样的效果。

你已经做到了!Argparse只打印它找到的第一个错误,因此虽然它看起来只是在检查-k,但实际上它也会重复出现-n/-t。你可以通过给它-k参数看到这一点


如果提供-k参数,错误消息将从
test.py:error:argument-k/--kick\u start is required
更改为
test.py:error:arguments-n/--name-t/--template之一required

谢谢,我在学习Python时不知道它:)。还有一件事是如何检查参数是否有值。是否有一些空的(C++)类函数。如果它不相关,你应该单独问一个问题(当然,在检查了它还没有被问过之后),但是。。。这取决于你到底想做什么。Python有一个“真实性”的概念,因此您可以只使用
if variable:
if not variable:
。除此之外,您可以在容器上使用例如
len(variable)==0
,或者
variable is None
来检查它是否为None。或者只需与所讨论类型的空值进行比较。
argparse
参数的默认值为
None
。因此,
print args.name为None
将打印
True
。默认的
args.quiet
False