pythonargparseoptparse

Will switching to argparse let me use the same flag with different meanings between subcommands?


We're currently using optparse for our command-line interface, and it's about 75% of what we'd like. I've read up on some argparse, and came away thinking that perhaps the ability to have a parent parser and children parsers will get us the rest of the way.

Let me explain: We have way too many command-line options, such that we've run out of letters in the alphabet to distinguish them from each other. Will having a parent parser with multiple child parsers allow the re-use of some of our flags? Currently the user will enter something like:

python myprog.py -c run_and_hide -t red -n 14

But we'd also like that to use -t for a different option:

python myprog.py -c lie_down_and_sing -t orangutan -f fruit

optparse won't let me use -t for more than one option. I know that optparse allows us to put in long options:

python myprog.py -c run_and_hide --color-of-shirt red -n 14

but I'd like to not have to go that route. So, does argparse have that capability?

The second thing that would be the bee's knees is the ability to only print out part of the help message. As you can guess, the help message for our app is rather lengthy. We'd like to be able to look at what "command" (run_and_hide vs. lie_down_and_sing) drew an error, and print only the segment of the help message that pertains. I was wondering if setting up a child parser for each of our "command" options, and then going to that parser and printing the help would be possible.

Thanks!


Solution

  • If you restructure your parser such that run_and_hide, lie_down_and_sing, &c. are subcommands with their own subparsers, you will indeed be able to use the same flag with a different meaning between those subparsers.