-1

I want to recreate [-A [-b value]] where in command would look like this:

test.py -A -b 123

Seems really simple but I can't get it right. My latest attempt has been:

byte = subparser.add_parser("-A")
byte.add_argument("-b", type=int)
OriolAbril
  • 7,315
  • 4
  • 29
  • 40
Panda
  • 51
  • 1
  • 8
  • `add_parser` should probably return an error if you attempt to use an option name as an argument. – chepner Apr 05 '18 at 22:13
  • it does, the code above returns, error: invalid choice: '123' (choose from '-A') – Panda Apr 05 '18 at 22:23
  • No, I mean the call to `add_parser` itself, not when you call `parse_args()`, because such a subcommand appears to be buggy, at best. – chepner Apr 05 '18 at 22:30

1 Answers1

0

While the add_parser command accepts '-A', the parser cannot use it. Look at the help:

usage: ipython3 [-h] {-A} ...

positional arguments:
  {-A}

optional arguments:
  -h, --help  show this help message and exit

A subparser is really a special kind of positional argument. To the main parser, you have effectively defined

add_argument('cmd', choices=['-A'])

But to the parsing code, '-A' looks like an optional's flag, as though you had defined

add_argument('-A')

The error:

error: argument cmd: invalid choice: '123' (choose from '-A')

means that it has skipped over the -A and -b (which aren't defined for the main parser), and tried to parse '123' as the first positional. But it isn't in the list of valid choices.

So to use subparsers, you need specify 'A' as the subparser, not '-A'.

hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • Gotcha, I have tried this way also before posting with error, unrecognized arguments -B -s. And as you and cheapner (comments above) have mentioned, I do the unorthodox declaration of -A, -t, etc. within " " but out of all videos/tutorials I have yet to see a formal declaration for input >> test.py -a 123 -t ph – Panda Apr 06 '18 at 06:44
  • Like you said add_argument does allow "-A", with subparser, however, this won't cut it – Panda Apr 06 '18 at 06:47