0

I have read a similar question asked on SO, which doesn't address my own problem. For illustration purpose, say I have a Python program using argpase that provides two subcommands: copy and resume:

prog copy src dest # src, dest positional, required prog resume id # id positional, required 

However, the most natural way to invoke the "copy" command is NOT explicitly give the copy subcommand, that is, I was hoping for:

prog src dest 

will do the default copy action, while still keep the benefits of have two subparsers, each handles a different set of arguments. Is it possible with argparse package?

1 Answer 1

1

Formally there isn't. The subcommand argument is a required positional argument, where the 'choices' are the subparser names (and their aliases).

That's evident in the help message, were {cmd1,cmd} are shown as choices.

usage: ipython3 [-h] {cmd1,cmd2} ... positional arguments: {cmd1,cmd2} optional arguments: -h, --help show this help message and exit 

The latest Python has a 'bug' that actually lets it be optional. In other words, it does not raise an error if you don't give any positionals. It's a bug because it changes previous behavior, and most people what it to be required. But even when it is optional, and cmd1 defined as the default, it won't run the cmd1 parser on the remaining arguments. And any 'positional' argument will be treated as a wrong command string.

I think the best you can do is define one or more positionals. One might have choices and default, and be optional (nargs='?'). The rest (or other) might has nargs='+'. By playing around with those options you could approximate the desired behavior, but it won't make use of the subparsers mechanism.


Another way to think about the issue, is to consider an input like

prog one two 

Should it interpret that as prog src dest or prog cmd id. The only basis for saying it should be the former is the fact that one is not one of copy or resume. But it isn't that smart when it comes to handling 'choices'. It assigns a value based on position, and then tests whether it meets criteria like 'choices' or 'type' (ie. integer, float v string).

Sign up to request clarification or add additional context in comments.

1 Comment

Though it is not exactly what I am hoping for, but I think it is as good as it gets. Thanks for taking the time to explain.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.