Search code examples
pythonargparsesubparsers

Python argparse subparser valid usage?


I am planing to write a command using the argparse library, this is my command structure:

$ python cvs.py -d my_adress local diff -r xyz -N -d details

Here, the local has multiple command grouped to it such as local commit, local add etc. E.g. [-d my_address] is parsed in main and all switches after local diff are parsed together by a function executed for local diff.

Similarly, there is another command group parallel to local; say global.

The switch -d is not mixed with -r. So, the parser parsing -r doesn't know about -d and vice versa.

Is it possible to implement this using argparse? If yes, can somebody suggest me a rough algorithm to do this. If no, What are other possible way to do this in python? Thanks.


Solution

  • See the nargs parameter, namely the '*' option. It won't do a subparse (I do not think that argparse can to that at all), but it will at least group your options so you'll get -d and -r returned as separate options. -N won't be a known option. I don't know whether argparse would consider it an error (which you don't want), or just another parameter of -r.

    Your approach might fail. CVS subcommands can have all sorts of one-letter options like -d, -r, etc. (it's a long list). You'll find yourself constantly making hard choices of whether you want to support a specific CVS option as a subcommand or rather use the letter for your cvs.py option.

    You could introduce some markup to separate CVS subcommands, i.e. python cvs.py -d my_adress local diff § -r xyz -N. However, that's not a real improvement over cvs -d my_adress local diff; cvs -r xyz -N anymore.