python - Argparse 通过分组互斥

标签 python argparse

目前我的代码的 argparse 给出了以下内容:

usage: ir.py [-h] [-q  | --json | -d ]

Some text

optional arguments:
  -h, --help            show this help message and exit
  -q                    gene query terms (e.g. mcpip1)
  --json                output in JSON format, use only with -q
  -d , --file_to_index  file to index 

我想要它做的是:

  1. -q 应该与 -d
  2. 互斥
  3. --json 应该只与 -q
  4. 一起使用

有什么办法吗? 这是我的 argparse 代码:

parser = argparse.ArgumentParser(description='''Some text''')
group = parser.add_mutually_exclusive_group()
group.add_argument("-q",help="gene query terms (e.g. mcpip1)",metavar="",type=str)
group.add_argument("--json", help="output in JSON format, use only with -q", action="store_true")
group.add_argument("-d","--file_to_index", help="file to index",metavar="",type=str)
args = parser.parse_args()

它目前拒绝使用 --json-q:

python ir.py --json -q mcpip1
usage: ir.py [-h] [-q  | --json | -d ]

ir.py: error: argument -q: not allowed with argument --json

最佳答案

-q-d不是真正的选择(大概,其中一个是必需的);它们是子命令,因此您应该使用 argparse 的子解析器功能创建两个子命令 queryindex , 和关联 --json只有 query子命令。

import argparse
parser = argparse.ArgumentParser(description='''Some text''')
subparsers = parser.add_subparsers()

query_p = subparsers.add_parser("query", help="Query with a list of terms")
query_p.add_argument("terms")
query_p.add_argument("--json", help="output in JSON format, use only with -q", action="store_true")

index_p = subparsers.add_parser("index", help="index a file")
index_p.add_argument("indexfile", help="file to index")

args = parser.parse_args()

整个程序的帮助可用

ir.py -h

每个子命令的帮助单独显示

ir.py query -h
ir.py index -h

用法类似于

ir.py query "list of terms"
ir.py query --json "list of terms"
ir.py index somefile.ext

关于python - Argparse 通过分组互斥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24009020/

相关文章:

python - 在 Python 中将十六进制字符串转换为百分比编码字符串

python - 在二叉搜索树中找到父级?

python - 访问参数帮助字符串中的 "implicit"元变量值

python - 当 argparse 指向路径名时,我怎么能默认什么都不做呢?

python - 使用 pandas 读取 gzip 文件不起作用

python - 使用逻辑填充缺失数据 Pandas

python - 如何在 Python 中实现二叉搜索树?

Python argparse 多个元变量名称

python - 我可以检查一个值是默认提供的还是用户提供的?

python - argparse 中子解析器之后的可选参数