nodeca/argparse

Document pattern for figuring out which subcommand is called.

Closed this issue · 1 comments

I found the Python docs/API to be pretty bad at this. No need to emulate them. As best I can tell, I should do something like:

const subparserKey = 'subparserName';
const subparsers = parser.addSubparsers({dest: subparserKey});

And then look at:

const parsedArgs = parser.parseArgs(args);
const whichSubparserWasCalled = parsedArgs[subparserKey];

Unfortunately, this is still a bit of a pain because whichSubparserWasCalled could be the full name of the subcommand or an alias. It would be nice to have something simple and unambiguous.

In Python, I do subparser.set_defaults(func=callback_fn) on all of my subparsers so that I can do:

args = parser.parse_args()
args.func(args)

It works, but it's quite a bit of indirection.

If you don't use aliases, parser.add_subparsers({ dest: 'name' }) will work just fine.

If you do use them, subparser.set_defaults({ name: 'qwerty' }) on each parser will also do the job, although a bit clunky.

Check for python solutions, for example, here's something:
https://stackoverflow.com/questions/59493715/resolve-argparse-alias-back-to-the-original-command

We don't have any plans to implement API different from python.

Hmm... that being said, I don't think callback_fn thing works here... should it? How useful is it?