0

The commandline interface that I want is something like this:

my-executable command REQUIRED_ARG
# or
my-executable command subcommand [--foo] [--bar]

So, I don't want REQUIRED_ARG to be required (and to be parsed) when the subcommand exists.

Mutually exclusive group is close to what I want, but I cannot add subparsers to it. Another approach was described here but that's not my case: I want REQUIRED_ARG not to be parsed at all in case of subcommand (and this also seems to be a hack).

f1u77y
  • 146
  • 4
  • Both `REQUIRED_ARG` and `subcommand` are positionals. Values are allocated to positionals based on position, not value. If a string is not in the subparsers list of `choices` it raises an error. – hpaulj May 03 '18 at 21:58
  • @hpaulj But `subcommand` is not positional argument, it's subparser. – f1u77y May 04 '18 at 03:34
  • To the main parser, a `subparser` is just a `positional` with a special `action` `_SubParsersAction`. The subparsers are `choices`. https://docs.python.org/3/library/argparse.html#sub-commands. – hpaulj May 04 '18 at 03:59
  • Due to a change in how `argparse` tests for required arguments, subparsers are now optional, at least in PY3. https://stackoverflow.com/questions/23349349/argparse-with-required-subparser. Any ways I think the linked answer is still relevant to this issue. – hpaulj May 04 '18 at 04:27
  • I'm not quite sure what you mean by `not to be parsed at all`. Do you mean don't complain if it's missing? Or ignore the string even if present? In `argparse` parsing is controlled by flags (e.g. '--foo') and by position. They aren't parsed conditionally based on their own value or value type, or value of other strings. – hpaulj May 04 '18 at 04:31
  • Another option is to parse the input a couple of times, once to identify some usage case (e.g. check `sys.argv[1]` for certain values), and again to parse that special situation. Ultimately the `argparse` parser is just a tool for figuring out what your user wants. It's not your whole program. – hpaulj May 07 '18 at 16:39

0 Answers0