1

In Python's argparse, how do you implement top-level arguments while still using commands implemented as subparsers?

I'm trying to implement a --version argument to show the program's version number, but argparse is giving me error: too few arguments because I'm not specifying a sub-command for one of the subparsers.

My code:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
    '-v', '--version',
    help='Show version.',
    action='store_true',
    default=False
)
subparsers = parser.add_subparsers(
    dest="command",
)
list_parser = subparsers.add_parser('list')
parser.parse_args(['--version'])

the output:

usage: myscript.py [-h] [-v] {list} ...
myscript.py: error: too few arguments

2 Answers 2

4

If you only need version to work, you can do this:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument(
    '-v', '--version',
    action='version',
    version='%(prog)s 1.0',
)

Subparsers won't bother any more; the special version action is processed and exits the script before the parser looks for subcommands.

Sign up to request clarification or add additional context in comments.

Comments

2

The subparsers is a kind of positional argument. So normally that's required (just as though you'd specified add_argument('foo')).

skyline's suggestion works because action='version' is an action class that exits after displaying its information, just like the default -h.

There is bug/feature in the latest argparse that makes subparsers optional. Depending on how that is resolved, it may be possible in the future to give the add_subparsers command a required=False parameter. But the intended design is that subparsers will be required, unless a flagged argument (like '-h') short circuits the parsing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.