How can I set a subparser to be optional in argpar

2020-07-24 05:46发布

问题:

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