I'm writing a CLI tool that needs to accept 2 different flavors of a "search" command as its first argument : one that requires exactly 1 extra positional argument and the other exactly 3 extra positional arguments.
e.g. : tool search x
or tool search x y z
would both be valid (not tool search x y
), but route to completely different functionality.
There are also a few other commands besides "search". I also need to be in control of the exact error messages and exit codes (I think this is possible with ArgumentParser.exit() )
How would you implement this with argparse ? Intuitively I think I need to use add_argument
twice for search
with different nargs
and possibly different dest
, but not sure if this is possible.
Honestly I was going to do this directly with sys.argv
but I keep reading how naughty that is (I can see why, but this seems like a special case), so just checking if this is easy to do with argparse as well.
Thanks.