0

I want my program to accept two modes:

myprogram mode1 --m_p 12 --m_q 13 --m_r 14

myprogram mode2 --n_p 15 --n_q 16 --n_r 17

and I wrote

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()

m = subparsers.add_parser('mode1')
m.add_argument("--m_p", type=str, required=True)
m.add_argument("--m_q", type=str, required=True)
m.add_argument("--m_r", type=str, required=True)

n = subparsers.add_parser('mode2')
n.add_argument("--n_p", type=str, required=True)
n.add_argument("--n_q", type=str, required=True)
n.add_argument("--n_r", type=str, required=True)

Now I want mode mode1 be default optional, i.e. if I run

myprogram mode1 --m_p 12 --m_q 13 --m_r 14

it will do the same as

myprogram --m_p 12 --m_q 13 --m_r 14

How this can be done?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Dims
  • 47,675
  • 117
  • 331
  • 600
  • 1
    No. The `subparsers` argument is a positional. The "mode1" string prompts that argument to `take_action`, which then starts the `m` parser, which handles the rest of the arguments. Without the `mode1' there's nothing to run `m`. Ordinary `defaults` just put a string or `type(string)` in the `args` namespace. – hpaulj May 14 '20 at 16:18
  • @hpaulj You posted some answers [here](https://stackoverflow.com/q/46667843/4518341) which might be useful. The idea of parsing known args then passing off the rest to another parser seems like the best option here. – wjandrea May 14 '20 at 22:11
  • 1
    As originally written, a subparser was required as normal positional would be. But because of some oversights in other code changes, it is now optional (unless `required`). But you should also set the `dest`. If you don't want to play by the `argparse` rules, be prepared to do more work and debugging. – hpaulj May 15 '20 at 01:29

0 Answers0