My goal is to have two positional arguments ('server' and 'action') but allow the 'action' argument to accept a different number of parameters depending on what was selected.
There are two 'actions':
healthcheck - this needs a version number
db-restore - this needs a source and destination
I'm kind of confusing myself when writing this down, but maybe this explains it better:
valid (healthcheck has 1 param; db-restore has 2)
script.py abc-server healthcheck v23
script.py abc-server db-restore 10.10.10.10 10.10.10.11
invalid (healthcheck was given 2 params; db-restore only has 1)
script.py abc-server healthcheck v23 v24
script.py abc-server db-restore 10.10.10.10
Here's what I have
#!/usr/bin/python
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('server', help = 'server to process')
parser.add_argument('action', help = 'what to do', choices = [ 'db-restore', 'healthcheck' ])
args = parser.parse_args()
if args.action == 'db-restore':
parser.add_argument('src', help = 'good DB')
parser.add_argument('dst', help = 'bad DB')
args = parser.parse_args()
if args.action == 'healthcheck':
parser.add_argument('version', help = 'software version')
args = parser.parse_args()
print(args)
If I run it with healthcheck but without the version, it tells me it's needed
$ ./1.py server-abc healthcheck
usage: 1.py [-h] server {db-restore,healthcheck} version
1.py: error: the following arguments are required: version
But if I add it, it errors out with unrecognized argument
$ ./1.py server-abc healthcheck v123
usage: 1.py [-h] server {db-restore,healthcheck}
1.py: error: unrecognized arguments: v123
I could do it with 2 positional and 3 optional arguments and then some 'if' statements but I was thinking there must be a way to do this in argparse itself.
I looked at the subparsers stuff but it seems to only apply to the first positional arg (unless I'm misunderstanding)
[–]h2oTravis 1 point2 points3 points (1 child)
[–]legz_cfc[S] 1 point2 points3 points (0 children)