0

I want to create such a thing:

program.py list contracts --minc MIN --maxc MAX

in which --XXXc corresponds with contracts. The positional params (which actions to be performed) may be up to 3 (list, contracts, ticks - at least one, maximum of 3), and the optional args will specify the flags for a certain action. But with the code below it gives me this weird presentation (no clue whether this "{list,contracts,ticks} [{list,contracts,ticks} ...]" will be understandable for the user):

usage: program.py [-h] [--minc MIN] [--maxc MAX] {list,contracts,ticks} [{list,contracts,ticks} ...]

  parser = argparse.ArgumentParser()
  parser.add_argument("action", nargs='+', choices=("list","contracts","ticks"), help="choose from: list, contracts, and/or ticks", type=str)
  parser.add_argument('--min', type=int)
  parser.add_argument('--max', type=int)
  args = parser.parse_args()
  if ('contracts' in args.action):
    if (args.min > 4):
    ...
  else
    pass # not checking the --min for non-contracts

I read about add_subparsers but then the user must first run program.py list before flags would be visible.

Also, I tried to make "[{list,contracts,ticks} ...]" more readable by tweaking ArgumentParser()'s add_help param but it did not lead to changes.

Mat90
  • 169
  • 1
  • 9
  • `argparse` is not a good tool for this. Parse `sys.argv` directly. – hpaulj Jun 06 '21 at 09:34
  • 1
    What you defined was two flagged arguments, named `min` and `max` that accept an integer value. And one positional argument that takes one or more strings, and each of those strings has to be one of those choices. `args.action` will be a list of strings. There is no `args.contracts` value. Add a `print(args)` statement to your code to get a clear idea of what the parser did. – hpaulj Jun 06 '21 at 18:59
  • To better understand the `{}` usage, make an argument without choices, or one without the nargs and look at their help. – hpaulj Jun 06 '21 at 20:29
  • Thank you. The args.contracts was a typo in order to make it a little more compact. I changed the code a little. It now works, as long as I use only flags/optional params (else it will be nagging about not fitting the 3 choices). The {list,contracts,ticks} designates one out of 3 required, and [{list,contracts,ticks}] yet another one of 3 but now optional I guess, and the latter can be repeated as designated by "...". – Mat90 Jun 09 '21 at 19:14

0 Answers0