Python argparse:互斥的必需组与必需选项

30 投票
1 回答
19443 浏览
提问于 2025-04-18 09:01

我正在尝试创建一个必须选择的互斥组,其中有一个必填的参数。下面是我写的代码:

#!/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。请问该怎么做到这一点呢?

1 个回答

20

你已经做到了!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

撰写回答