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

查看:49
本文介绍了如何在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/问题

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天全站免登陆