argparse up to 3 positional arguments, optional flags for each

566 Views Asked by At

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.

0

There are 0 best solutions below