Only one command line option with argparse
Pergunta
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?
Solução
This is what you probably want:
http://docs.python.org/library/argparse.html#sub-commands
With this you can add sub arguments which have their own argument schemes.
Outras dicas
@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
By default, argparse arguments consume one value. If you want foo to have different behavior, you'll need to specify it. It looks like you think the default is nargs=0, but it's not. From the argparse documentation (at http://docs.python.org/dev/library/argparse.html#nargs): "If the nargs keyword argument is not provided, the number of args consumed is determined by the action. Generally this means a single command-line arg will be consumed and a single item (not a list) will be produced."
You can either use nargs='?' for foo and give it a default value in case nothing is provided from the command-line, or use a non-default action (perhaps 'store_true'?).