4

I need to specify command line parameters depending on another parameter. So the first specified parameter should specify the action and the following the arguments for that action.

python test.py create -d what -s size -t type
python test.py delete -d what -a now
python test.py status -x something

Is there a framwork/library with which this can easily be done? I have looked into argparse so far but couldn't find anything that could do this?

1 Answer 1

4

The problem is that argparse is absolutely gigantic and I guess that's why you couldn't find it easily, but if you had read through the entire documentation (or knew the terms to look for) you would find that the concept of subcommands will probably achieve what you want to do. Here is a very quick and simple example:

import argparse

parser = argparse.ArgumentParser(prog='PROG')
subparsers = parser.add_subparsers(dest='command', help='sub-command help')
parser_create = subparsers.add_parser('create')
parser_create.add_argument('-d')
parser_create.add_argument('-s')
parser_create.add_argument('-t')

parser_delete = subparsers.add_parser('delete')
parser_delete.add_argument('-d')
parser_delete.add_argument('-a')

parser_status = subparsers.add_parser('status')
parser_status.add_argument('-x')

A simple usage:

>>> p = parser.parse_args(['create', '-d', 'what', '-s', 'size', '-t', 'type'])
>>> p.command
'create'
>>> p.d
'what'

>>> p = parser.parse_args(['delete', '-d', 'what', '-a' 'now'])
>>> p.command
'delete'
>>> p.a
'now'

Of course, check out the documentation for all the details, like using dest to give it more meaningful names (which you can see being used with the add_subparsers call in the example).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.