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
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.