0

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.

renaudg
  • 662
  • 6
  • 11
  • Why not capture all arguments, and then validate them with your own custom logic (prior to the script's main execution)? – alex Sep 11 '19 at 15:23
  • Good idea, but is there much value left in using argparse when you do that ? – renaudg Sep 11 '19 at 15:29
  • `argparse` is most useful if you're parsing command line options. If your only use is for positional arguments, you're getting less value out of it. But, you still get thinsg like: (a) help output with --help (b) errors for unknown options (c) an easy way to add optional arguments in the future. – larsks Sep 11 '19 at 15:31
  • I think https://stackoverflow.com/questions/8624034/python-argparse-type-and-choice-restrictions-with-nargs-1 might help - not sure if it's possible to accomplish this natively. I think you're going for something like `choices=[["x"], ["x", "y", "z"]]` but I don't think that's possible. In either case, you'd want to hinge your script's execution flow based off of which choice is provided - so I'd be inclined to create a custom validation script and route execution based off that. – alex Sep 11 '19 at 15:34
  • You can use `add_argument('foo', nargs=2)` and `add_argument('foo', nargs=4)` together, but that means you want 6 strings total. There's no either/or when it comes to specifying `positionals`. – hpaulj Sep 11 '19 at 15:47

0 Answers0