选项的 argparse 选项 [英] argparse option of options
问题描述
我正在尝试在 argparse
中添加选项选项.目前我有:
I am trying to add option of options in argparse
.
Currently I have:
group = parser.add_mutually_exclusive_group()
group.add_argument("--md", help="Create xyz file for each ionic step for"
" visualization", action='store_true')
group.add_argument("--force", help="See which atom has maximum force",
action='store_true')
group.add_argument("--opt", help="grep string from file",
nargs=2, metavar=("str", "file"))
parser.add_argument("--xsf", help="Create xsf file for md(default is xyz)"
" visualization", action='store_true')
parser.add_argument("-N", help="Showing first N line",
metavar='integer', type=int)
parser.add_argument("-n", help="Showing last n line",
metavar='integer', type=int)
args = parser.parse_args()
给出:
./foo.py --h
usage: foo.py [-h]
[--md | --force | --opt str file]
[--xsf] [-N integer] [-n integer]
但我希望 --xsf
作为 --md
、-N、-n
的子选项 --opt代码>;例如
But I want --xsf
as a suboption for --md
, -N,-n
for --opt
; e.g.
./foo.py --h
usage: foo.py [-h]
[--md [--xsf]| --force | --opt str file [-N integer] [-n integer]]
但我不知道如何实现.可能是我遗漏了一些东西,但在 argparse doc 中没有这样的选项
But I dont know how to achieve that. May be I am missing something, but there is no option like that in argparse doc
还有其他方法可以得到吗?
Is there any other way of getting that?
推荐答案
mutually_exclusive_group
机制非常简单,不适用于任何类型的嵌套或子分组.
The mutually_exclusive_group
mechanism is quite simple, and does not work with any kind of nesting, or subgrouping.
有一个 Python 错误/问题需要更全面的分组机制,但提议的补丁相当复杂.问题不仅在于测试,还在于以用户友好的方式定义组,以及生成 usage
行.很高兴您包含了所需的用法,但该格式远远超出了当前帮助格式化程序的功能.
There is a Python bug/issue requesting a more comprehensive grouping mechanism, but the proposed patch is rather complicated. The problem isn't just with testing, it's with defining the groups in a user friendly way, and with generating the usage
line. It's nice that you included a desired usage, but that format is well beyond the capabilities of the current help formatter.
您可能会考虑将您的问题重新定义为子解析器问题.子解析器是互斥的(您只能给出一个命令名称),您可以指定 --xsf
作为 md
和 -N
的参数> 作为 --opt
的参数.但是子解析器有其自身的帮助问题.
You might look into recasting your problem as a subparser one. subparsers are mutually exclusive (you can only give one command name), and you could specify --xsf
as an argument for md
, and -N
as argument for --opt
. But subparsers has its own help issues.
另一种方法是编写自己的用法
,并在解析后对参数进行自己的测试.With a suitable choice of defaults you can usually tell whether an argument has been provided or not (the user can't specify None
) or you can ignore unnecessary ones.
Another route is to write your own usage
, and do your own testing of arguments after parsing. With a suitable choice of defaults you can usually tell whether an argument has been provided or not (the user can't specify None
) or you can ignore unnecessary ones.
这篇关于选项的 argparse 选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!