0

I have a Python program (currently Python 2.7, still undecided about upgrading to Python 3) that receives arguments via argparse, with one positional argument whose length is variable (nargs="+"). I need to add another option which also has a variable length.

I saw that argparse has some kind of support for two variable length arguments but since one of them in my case is positional it means that it creates ambiguity if the end user happens to pass the new variable length option as the last option before the positional argument. Changing the positional argument to be named will break existing APIs so it's not possible unfortunately.

I also thought about the possibility of specifying the same option multiple times (e.g. -c val1, -c val2, -c val3 etc.), which is pretty much the same as this question: Using the same option multiple times in Python's argparse, but that question does not have a direct answer (only workarounds, which assume that there is no more than one variable length argument so not really useful to me).

Any ideas what is the best approach here will be greatly appreciated.

Dan
  • 11
  • 2
    Your question might be easier to understand if you add some examples. – Klaus D. Apr 27 '20 at 08:22
  • As you say, `argparse` can't tell where one argument ends and the next starts. Ideally if the 2nd is '+' it should reserve one value for that. With 2 positionals it might just do that (I'd have to test). But in general reserving a string for a latter argument requires a kind of look-ahead that `argparse` does not do. – hpaulj Apr 27 '20 at 15:10

2 Answers2

0

You can specify an optional field that requires a flag:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("A", nargs="+")
parser.add_argument("--b", nargs="+")

args = parser.parse_args(
  ["a", "b", "c", "d", "--b", "1", "2", "3"]
)

print(args)
# Namespace(A=['a', 'b', 'c', 'd'], b=['1', '2', '3'])

All this requires is that the other variable length option is specified after the positional arguments.


As a note, seeing how python 2.7 is no longer maintained (as of 01/01/2020) you could move to python 3, and make your breaking changes now.

Alex
  • 6,610
  • 3
  • 20
  • 38
0

OK I think that action='append' may do what I'm looking for.

Dan
  • 11