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

混江龙づ霸主 提交于 2019-12-09 22:35:23

问题


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.

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

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


回答1:


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



来源:https://stackoverflow.com/questions/35570139/how-can-i-set-a-subparser-to-be-optional-in-argparse

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