i have an ArgumentParser
with sub-parsers. Some flags are common for all sub-parsers, and I would like to be able to specify them either before or after the sub-command, or even mix before and after (at the user’s discretion).
Something like this:
$ ./test -v
Namespace(v=1)
$ ./test.py test -vv
Namespace(v=2)
$ ./test.py -vvv test
Namespace(v=3)
$ ./test.py -vv test -vv
Namespace(v=4)
So I tried something like this:
#!/usr/bin/env python3
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-v", action="count")
subparsers = parser.add_subparsers()
sub = subparsers.add_parser("test")
sub.add_argument("-v", action="count")
print(parser.parse_args())
Running this program “test.py” gives me:
./test.py -h
usage: test.py [-h] [-v] {test} ...
positional arguments:
{test}
options:
-h, --help show this help message and exit
-v
$ ./test.py test -h
usage: test.py test [-h] [-v]
options:
-h, --help show this help message and exit
-v
$ ./test.py -v
Namespace(v=1)
$ ./test.py test -vv
Namespace(v=2)
cool.
but it also gives me:
$ ./test.py -vvv test
Namespace(v=None)
$ ./test.py -vv test -vv
Namespace(v=2)
less cool 🙁
I also tried to specify parent-parsers explicitly:
common = argparse.ArgumentParser(add_help=False)
common.add_argument("-v", action="count")
parser = argparse.ArgumentParser(parents=[common])
sub = parser.add_subparsers().add_parser("test", parents=[common])
print(parser.parse_args())
but the result is the same.
So, I guess that as soon as the test
subparser kicks in, it resets the value if v
to None
.
How do I prevent this?
(I notice that How can I define global options with sub-parsers in python argparse? is similar, and the answer there suggests to use different dest
variables for the top-level and the sub-level parser. i would like to avoid that…)