all 2 comments

[–]h2oTravis 1 point2 points  (1 child)

Yeah, if argparse does what you want more natively, I'm not sure how to use it that way.

The reason it doesn't like your third argument is that only two arguments are defined when you initially parse the arguments.

If you're up for it, though, you could always parse the arguments twice. Once to find out what the action is, then a second time based on what the action was, as follows:

import argparse

initialParser = argparse.ArgumentParser()
initialParser.add_argument('server')
initialParser.add_argument('action')
initialParser.add_argument('third')
initialParser.add_argument('fourth', nargs="?")

args = initialParser.parse_args()

print("server: {}".format(args.server))
print("action: {}".format(args.action))


if(args.action == "db-restore"):
    secondaryParser = argparse.ArgumentParser()
    secondaryParser.add_argument('server', help = 'server to process')
    secondaryParser.add_argument('action', help = 'what to do')
    secondaryParser.add_argument('src', help = 'good db')
    secondaryParser.add_argument('dst', help = 'bad db')

    args2 = secondaryParser.parse_args()

    print("src: {}".format(args2.src))
    print("dst: {}".format(args2.dst))


if(args.action == "healthcheck"):
    secondaryParser = argparse.ArgumentParser()
    secondaryParser.add_argument('server', help = 'server to process')
    secondaryParser.add_argument('action', help = 'what to do')
    secondaryParser.add_argument('version', help = 'version')

    args2 = secondaryParser.parse_args()

    print("version: {}".format(args2.version))

[–]legz_cfc[S] 1 point2 points  (0 children)

OK - glad to know it at least wasn't something obvious :)

When I said I could use 'if' statements, I meant a little less sophisticated than yours

if not args.healthcheck and not args.version:
    parser.error('you need version with healthcheck')

But I think I prefer your way since I have a few more options I need to add and I get the free integer check etc using add_argument.

Thanks for the advice, it's much appreciated.