如何在 argparse 中将子解析器设置为可选? [英] How can I set a subparser to be optional in argparse?

查看:27
本文介绍了如何在 argparse 中将子解析器设置为可选?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import argparse

parser_sub = subparsers.add_parser('files')
parser_sub.add_argument(
'--file-name',
action='store',
dest='filename',
nargs='*')

options = parser.parse_args()

输出:错误:参数太少.

Output: error: too few arguments.

根据此链接:https://bugs.python.org/issue9253 它指出子解析器不能是可选的.这种行为可以改变吗?

As per this link: https://bugs.python.org/issue9253 it states that subparsers cant be optional. Can this behaviour be changed?

我希望我的子命令是可选的.我如何通过 python 2.6 中的 argparse 实现这一点?

I would like my subcommands to be optional. How can I achieve this through argparse in python 2.6?

推荐答案

没有太多可以添加到那个 bug/issue https://bugs.python.org/issue9253.

There's not much that can be added to that bug/issue https://bugs.python.org/issue9253.

subparsers 是一种特殊的位置参数.通常,使位置可选的唯一方法是使用 nargs='?' 参数.

subparsers is a special kind of positional argument. Normally the only way to make a positional optional is with the nargs='?' parameter.

正如错误问题中所详述的那样,在最近的版本中,子解析器无意中成为了可选的.这是解析器检查所需参数的方式发生变化的结果.

As detailed in the bug issue, in recent versions, subparsers have inadvertently been made optional. That's a result of a change in how the parser checks for required arguments.

我不会说不可能在 2.6 版本中改进这种行为,但这不是你可以只用一两个参数值来做的事情.我认为这需要对这个错误/问题有一个很好的理解.它要么需要对 parse_args 进行代码更改,要么需要自定义 subparser Action 类.

I won't say it is impossible to retrofit this behavior into the 2.6 version, but it's not something you can do with just a parameter value or two. I think it would require a good understanding of this bug/issue. It either requires a code change to parse_args, or maybe a custom subparser Action class.

在早期版本中,缺少的子解析器字符串将被捕获:

In earlier versions, a missing subparser string will be caught by:

    # if we didn't use all the Positional objects, there were too few
    # arg strings supplied.
    if positionals:
        self.error(_('too few arguments'))

其中 positionals 是位置操作列表.当一个位置被处理时,它会从这个列表中删除.即使没有字符串(因为接受空列表),带有 ? 和 '*' 的动作也会被处理.所以没有看到 positionals 中剩下的任何东西.

where positionals is a list of positional Actions. When a positional is processed it is removed from this list. Actions with ? and '*' get processed even if there's no string (since the accept empty lists). So anything left in positionals was not seen.

较新的版本放弃了此测试,取而代之的是对 required 属性的测试(该属性已用于测试 optionals).

Newer versions dropped this test, substituting instead a test on the required attribute (which was already being used to test optionals).

这篇关于如何在 argparse 中将子解析器设置为可选?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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