2

I need to have a command line in the form

python script.py --step1=100 --step3=53 --step2=34

The requirements are

  • I don't know how many --stepN flags there are in advance
  • The order of the --stepN flags are not set, so I cannot just use action='append'

I'm also interested in these restrictions too:

  • The step numbers should be continuous, so if --step20 is used but --step19 is missing, this is an error.
  • I want the destination of the values in one list. So in the above command line example, I want to do something like
args = parser.parse_args()
args.steps # is list [100, 34, 53]

Can argparse take a pattern of agruments, and somehow I can write a custom action or type to do what I want? I'm thinking something like

parser.add_argument('--step*',
                    type=CustomType,
                    action=CustomAction,
                    help='Use --step1=a --step2=b, ....')
Vít Kotačka
  • 1,472
  • 1
  • 15
  • 40
DrBear
  • 31
  • 4

1 Answers1

3

This is not a good argparse fit. There have been a number of questions about accepting generalized key=value inputs, and various kludgey answers. For the most part the answers amount to parsing the strings yourself, either from sys.argv or the extras of parse_known_args.

Create variable key/value pairs with argparse (python)

This is doubly true with your added requirements about the form of the key.

In the latest such question I suggested using append and nargs=2 so the input would be of the form:

python script.py --step 1 100 --step 2 53 --step 3 34

producing

Namespace(step=[[1,100], [2,53], [3, 24]])

which you could process and value check to your heart's content.

Support arbitrary number of related named arguments with Python argparse

hpaulj
  • 221,503
  • 14
  • 230
  • 353