【问题标题】:Python argparse: Mutually exclusive required group with a required optionPython argparse:具有必需选项的互斥必需组
【发布时间】:2014-07-29 01:57:06
【问题描述】:

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

#!/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 成为强制性的。如何达到同样的效果。

【问题讨论】:

    标签: python python-2.7 argparse


    【解决方案1】:

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

    如果提供 -k 参数,错误消息将从 test.py: error: argument -k/--kick_start is required 更改为 test.py: error: one of the arguments -n/--name -t/--template is required

    【讨论】:

    • 谢谢,我在学习 Python 时并不知道 :)。还有一件事是如何检查参数是否有价值。是否有一些类似空(C++)的函数。
    • 如果它不相关,你真的应该问一个单独的问题(当然,在检查它还没有被问过之后),但是......这取决于你到底想做什么。 Python有一个“真实性”的概念,所以你可以use the variable directly in an if-clause or whatever,例如。 if variable:if not variable:。除此之外,您可以使用例如。 len(variable) == 0 在容器上或 variable is None 以检查它是否具体为无。或者只是与相关类型的空值进行比较。
    • argparse 参数的默认值为None。因此print args.name is None 将打印Trueargs.quiet 的默认值为 False
    猜你喜欢
    • 2016-05-24
    • 2021-08-08
    • 2011-07-31
    • 2017-01-15
    • 2012-05-25
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多