目前我的代码的 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
我想要它做的是:
-q
应该与-d
互斥
- 和
--json
应该只与-q
一起使用
有什么办法吗? 这是我的 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
的子解析器功能创建两个子命令 query
和 index
, 和关联 --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/