Tim Wilder
Tim Wilder

Reputation: 1647

Python and argparse: how to vary required additional arguments based on the first argument?

My goal is to write a Python command line utility using argparse that has multiple commands that each have different sets of required inputs.

I tried reading through the docs, a few Google searches, and stack overflow and couldn't find anything. I can think of a few possible solutions but they are ugly and require dealing with the help docs and validation manually. My suspicion is that this is the kind of problem with a common, effective solution already well enough known, and I am just lacking the right terms to search for it, or it is obscure enough by a small margin that it isn't posted in many places.

The best idea I have right now is to have one positional argument, and somehow have different requirements for a set of additional arguments based on the value of that input. Maybe I will parse twice?

As an example, this is a similar case:

There is one positional argument, animal

Options for animal are cat, lizard, fish

For cat, arguments claws, whiskers, paws are required

For lizard, arguments scale_color, favorite_food are required

For fish, argument water_type is required

We want the required additional arguments for each different animal value to be documented in -h without resorting to unorthodox practice.

I considered doing this with an optional argument for each of the main category choices. This is unattractive because the utility really only wants to take one of those arguments, and if I can avoid reinventing the wheel in terms of enforcing and documenting this, I would prefer to.

I could do something like:

valid_commands = ['a','b','c','d','e','f','g']
parser.add_argument('command', choices = valid_commands)
parser.add_argument('inputs', nargs = '*')

But then I don't have good input checks on the additional arguments for each command choice.

Is there some normal way this is done? Surely it is fairly common to write a utility that has several possible commands, and different required arguments for each. I could definitely get most of want I need by adding manual checks and help documentation, but this is the kind of thing I will probably do enough times that it's worth it to get it right on the first try.

Thanks for reading and let me know if I can help provide information.

Upvotes: 8

Views: 3242

Answers (1)

user104365
user104365

Reputation:

This seems to be what subparsers are for?

http://docs.python.org/dev/library/argparse.html#argparse.ArgumentParser.add_subparsers

Upvotes: 13

Related Questions