add_parser
with subparsers would do the trick
import argparse
parser = argparse.ArgumentParser(prog='script.py')
sp = parser.add_subparsers(dest='cmd')
for cmd in ['START', 'STOP', 'STATUS']:
sp.add_parser(cmd)
for cmd in ['MOVEABS', 'MOVEREL']:
spp = sp.add_parser(cmd)
spp.add_argument('x', type=float)
spp.add_argument('y', type=float)
parser.print_help()
args = parser.parse_args()
print(args)
producing the likes of:
2137:~/mypy$ python2.7 stack23304740.py MOVEREL -h
usage: script.py [-h] {START,STOP,STATUS,MOVEABS,MOVEREL} ...
positional arguments:
{START,STOP,STATUS,MOVEABS,MOVEREL}
optional arguments:
-h, --help show this help message and exit
usage: script.py MOVEREL [-h] x y
positional arguments:
x
y
optional arguments:
-h, --help show this help message and exit
and
2146:~/mypy$ python2.7 stack23304740.py MOVEREL 1.0 2.0
...
Namespace(cmd='MOVEREL', x=1.0, y=2.0)
and
2147:~/mypy$ python2.7 stack23304740.py START
...
Namespace(cmd='START')
The MOVEREL arguments could be named <x>
and <y>
, but then you'd have to access them via args['<y>']
instead of args.y
. metavar='<x>'
could be used to change the display but not the Namespace name.
You could also use spp.add_argument('point', nargs=2, type=float)
. Unfortunately there's a bug that keeps us from using a metavar in this nargs=2
case, http://bugs.python.org/issue14074.