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()
Edit: Please see quornian’s answer to this question, which is better than mine and should be the accepted answer.
According to the argparse documentation the result of
parser.parse_args(...)will “only contain attributes for the main parser and the sub parser that was selected”. Unfortunately this may not be enough information to determine which sub parser was used. The documentation recommends using theset_defaults(...)method on the sub parser to solve this problem.For example, I’ve added calls to
set_defaults()to your code:Now if you run
The result is
Check out the
add_subparsers()documentation for more information and another example.