How can I set a subparser to be optional in argparse?

≯℡__Kan透↙ 提交于 2019-12-04 15:39:58

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

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.

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'))

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!