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.

2
  • 2
    Your question might be easier to understand if you add some examples. Commented Apr 27, 2020 at 8: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. Commented Apr 27, 2020 at 15:10

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You can add required=True to make the named argument non-optional.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.