argparse: identify which subparser was used

user1062880 picture user1062880 · Nov 23, 2011 · Viewed 41.8k times · Source

I think this must be easy but I do not get it.

Assume I have the following arparse parser:

import argparse

parser = argparse.ArgumentParser( version='pyargparsetest 1.0' )
subparsers = parser.add_subparsers(help='commands')

# all
all_parser = subparsers.add_parser('all', help='process all apps')

# app
app_parser = subparsers.add_parser('app', help='process a single app')
app_parser.add_argument('appname', action='store', help='name of app to process')

How can I identify, which subparser was used? calling:

print parser.parse_args(["all"])

gives me an empty namespace:

Namespace()

Answer

quornian picture quornian · Feb 15, 2012

A simpler solution is to add dest to the add_subparsers call. This is buried a bit further down in the documentation:

[...] If it is necessary to check the name of the subparser that was invoked, the dest keyword argument to the add_subparsers() call will work

In your example replace:

subparsers = parser.add_subparsers(help='commands')

with:

subparsers = parser.add_subparsers(help='commands', dest='command')

Now if you run:

print parser.parse_args(["all"])

you will get

Namespace(command='all')