argparse选项的选项 [英] argparse option of options

查看:69
本文介绍了argparse选项的选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在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

还有其他方法吗?

推荐答案

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.

另一种方法是编写自己的usage,并在解析后对参数进行测试.通过选择适当的默认值,您通常可以判断是否已提供参数(用户无法指定None),或者您可以忽略不必要的参数.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆