When I use subcommands with python argparse, I can get the selected arguments.
JavaScript
x
9
1
parser = argparse.ArgumentParser()
2
parser.add_argument('-g', '--global')
3
subparsers = parser.add_subparsers()
4
foo_parser = subparsers.add_parser('foo')
5
foo_parser.add_argument('-c', '--count')
6
bar_parser = subparsers.add_parser('bar')
7
args = parser.parse_args(['-g', 'xyz', 'foo', '--count', '42'])
8
# args => Namespace(global='xyz', count='42')
9
So args
doesn’t contain 'foo'
. Simply writing sys.argv[1]
doesn’t work because of the possible global args. How can I get the subcommand itself?
Advertisement
Answer
The very bottom of the Python docs on argparse sub-commands explains how to do this:
JavaScript
1
10
10
1
>>> parser = argparse.ArgumentParser()
2
>>> parser.add_argument('-g', '--global')
3
>>> subparsers = parser.add_subparsers(dest="subparser_name") # this line changed
4
>>> foo_parser = subparsers.add_parser('foo')
5
>>> foo_parser.add_argument('-c', '--count')
6
>>> bar_parser = subparsers.add_parser('bar')
7
>>> args = parser.parse_args(['-g', 'xyz', 'foo', '--count', '42'])
8
>>> args
9
Namespace(count='42', global='xyz', subparser_name='foo')
10
You can also use the set_defaults()
method referenced just above the example I found.