Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only one command line option with argparse

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?

like image 882
errorhandler Avatar asked Nov 29 '22 16:11

errorhandler


1 Answers

@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
like image 84
mechanical_meat Avatar answered Dec 06 '22 00:12

mechanical_meat