带有子解析器和可选位置参数的Python argparse [英] Python argparse with subparsers and optional positional arguments

查看:35
本文介绍了带有子解析器和可选位置参数的Python argparse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有一个带有子解析器的程序,该程序可以处理特定的参数,同时还保留一些先前解析器的位置和可选参数(实际上,我真正想要的只是一个选项,一个有效的子解析器或一个有效的本地解析器)论点).

I would like to have a program with subparsers that handles specific arguments while also keep some positional and optional arguments to the previous parsers (In fact what I really want is only one option, I mean, a valid subparser OR a valid local argument).

我希望拥有的示例:程序[{sectionName [{a,b}]}] [{c,d}] .如果提供sectionName,则c/d不兼容,反之亦然.

Example of something I wish to have: Program [{sectionName [{a,b}]}] [{c,d}]. Being c/d incompatible if sectionName was provided and viceversa.

但是,我能做到的最好的就是这个 test.py [-h] {sectionName} ... [{c,d}] .这意味着,argparse不允许我在未指定有效的 sectionName 的情况下使用位置参数c或d.

However, the best I could achieve is this test.py [-h] {sectionName} ... [{c,d}]. This means, argparse don't allow me to use the positional arguments c or d without specifying a valid sectionName.

这是代码:

import argparse

mainparser = argparse.ArgumentParser()
# Subparser
subparser = mainparser.add_subparsers(title="section", required=False)
subparser_parser = subparser.add_parser("sectionName")
subparser_parser.add_argument("attribute", choices=['a', 'b'], nargs='?')
# Main parser positional and optional attributes
mainparser.add_argument("attribute", choices=['c', 'd'], nargs='?')

mainparser.parse_args()

我为此感到疯狂.任何帮助将不胜感激!

I'm getting crazy with this. Any help would be much appreciated!

我正在使用 Python 3.8

推荐答案

subparser 对象实际上是一个位置 Action ,需要 choices -在这种情况下为 {'sectionName'} .使用 nargs 模式分配字符串,按定义的顺序填充 positinal 参数.

The subparser object is actually a positional Action, one that takes choices - in this case {'sectionName'}. positinal arguments are filled in the order that they are defined, using the nargs pattern to allocate strings.

一旦主解析器获得"sectionName",它将把解析传递给 subparser_parser .比处理其余的输入,例如 {'a','b'} 位置信息.它无法处理的所有内容都放在无法识别"列表中,并且控件返回 main 进行最终处理. main 不做任何进一步的参数处理.因此,您的 attribute 参数将被忽略.

Once the main parser gets the 'sectionName' it passes the parsing to subparser_parser. Than handles the rest of the input, such as the {'a','b'} positional. Anything it can't handle is put on the 'unrecognized' list, and control returns main for final processing. main does not do any further argument processing. Thus your attribute argument is ignored.

您可以在 add_subparsers 之前放置一个 attribute 位置,但是我不会尝试使其成为 nargs ='?'.

You could put define a attribute positional before the add_subparsers, but I wouldn't try to make it nargs='?'.

因此,最好在子解析器之前定义所有 main 参数,并使用 optionals .这将提供最干净,最可靠的解析.

So it's best to define all main arguments before the subparsers, and to use optionals. This will give the cleanest and most reliable parsing.

这篇关于带有子解析器和可选位置参数的Python argparse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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