Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dynamic command line parameter

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?

like image 771
wasp256 Avatar asked Oct 28 '25 08:10

wasp256


1 Answers

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).

like image 190
metatoaster Avatar answered Oct 31 '25 03:10

metatoaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!