python - 正如在 argparse 中使用互斥参数一样?

标签 python argparse command-line-interface

来自命令行的一些数据(例如电子邮件地址)的必读列表:

some_util -l email1@x.com email2@x.com

或来自文件:

some_util -L email.lst

如何使其无法在 argparse 中使用两个键 -l 和 -L 的组合

import argparse
import sys
def createCLParser():
    parser = argparse.ArgumentParser()
    parser.add_argument('-l', '--list', nargs='+', help='list from comand line')
    parser.add_argument('-L', '--list-file', type=argparse.FileType(), help='list from file')
    return parser
if __name__ == '__main__':
    parser = createCLParser()
    namespace = parser.parse_args(sys.argv[1:])

argparse 中有一个方法add_mutually_exclusive_group (),但它必须是可选的。

最佳答案

使用.add_mutually_exclusive_group()方法 required=True:

import argparse
import sys
def createCLParser():
    parser = argparse.ArgumentParser()
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('-l', '--list', nargs='+', help='list from comand line')
    group.add_argument('-L', '--list-file', type=argparse.FileType(), help='list from file')

    return parser
if __name__ == '__main__':
    parser = createCLParser()
    namespace = parser.parse_args(sys.argv[1:])
    print namespace

用法:

$ python ar.py 
usage: ar.py [-h] (-l LIST [LIST ...] | -L LIST_FILE)
ar.py: error: one of the arguments -l/--list -L/--list-file is required

$ python ar.py -l foo@example.com
Namespace(list=['foo@example.com'], list_file=None)

$ python ar.py -l foo@example.com -L bar
usage: ar.py [-h] (-l LIST [LIST ...] | -L LIST_FILE)
ar.py: error: argument -L/--list-file: not allowed with argument -l/--list

关于python - 正如在 argparse 中使用互斥参数一样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25145106/

相关文章:

Python:argparse 读取 csv 文件以发挥作用

具有依赖关系的python argparse

python - 将文本字符串转换为 python 内的列表

python - 谁能告诉我 Python 中的合并排序有什么问题?

python - 使用 from sys import argv 输入

Python argparse 和 bash 完成

powershell - 使用 PowerShell 进行 Expect 和 Spawn

php - cli 上的相同 MySQL 转储命令和 PHP 返回不同

python - 将颜色打印到 python 命令行

python - Django休息框架: Display object only for specific choice