When I use subcommands with python argparse, I can get the selected arguments.
parser = argparse.ArgumentParser()
parser.add_argument('-g', '--global')
subparsers = parser.add_subparsers()
foo_parser = subparsers.add_parser('foo')
foo_parser.add_argument('-c', '--count')
bar_parser = subparsers.add_parser('bar')
args = parser.parse_args(['-g, 'xyz', 'foo', '--count', '42'])
# args => Namespace(global='xyz', count='42')
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?
The very bottom of the Python docs on argparse sub-commands explains how to do this:
You can also use the
set_defaults()
method referenced just above the example I found.Here's an example of simple task function layout using subparsers.