I'm trying to create a CLI with the argparse module but I'd like to have different commands with different argument requirements, I tried this:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('foo', help='foo help')
parser.add_argument('test', nargs=1, help='test help')
args = parser.parse_args()
what I'd like is to be able to run python test.py foo
and python test.py test somearg
but when I run python test.py foo
I get error: too few arguments
. Is there a way that the commands could behave like git status
, git commit
or pip install
? or is there a better way to create a CLI in python?
@crodjer is correct;
to provide an example:
import argparse
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(title='subcommands',
description='valid subcommands',
help='additional help')
foo_parser = subparsers.add_parser('foo', help='foo help')
bar_parser = subparsers.add_parser('bar', help='bar help')
bar_parser.add_argument('somearg')
args = parser.parse_args()
Test of different args per subparser:
$ python subparsers_example.py bar somearg Namespace(somearg='somearg') $ python subparsers_example.py foo Namespace() $ python subparsers_example.py foo somearg usage: argparse_subparsers.py foo [-h] subparser_example.py foo: error: unrecognized arguments: somearg
Help output:
$ python subparsers_example.py foo -h usage: argparse_subparsers.py foo [-h] optional arguments: -h, --help show this help message and exit $ python subparsers_example.py bar -h usage: argparse_subparsers.py bar [-h] somearg positional arguments: somearg optional arguments: -h, --help show this help message and exit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With