0

I want quotes around "arg1" "arg2" to be considered as separate arguments not in the same list and "arg1 arg2" as separate arguments but in the same list.

test.py taken from here

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--nargs', nargs='*')

for _, value in parser.parse_args()._get_kwargs():
  if value is not None:
    print(value)

run 1

python test.py --nargs "arg arg2"

output 1

['arg arg2']

I guess this is fine? But are arg and arg2 considered separate arguments?

run 2

python test.py --nargs "arg" "arg2"

output 2

['arg', 'arg2']

In the same list but are they considered separate arguments? I need them to be something like:

['arg'] ['arg2']
Bryn
  • 257
  • 4
  • 16
  • 4
    Your shell determines how arguments are separated, not python. Most shells will consider `"arg arg2"` to be a single argument and will pass it to python as such. If you want to separate the words into separate arguments, you'll have to do it in the usual ways (e.g. with `str.split()`). – glibdud Aug 10 '17 at 15:31
  • @Roelant The format: 'arg1' 'arg2' should be two separate args in two seperate rows whilst 'arg1 arg2' should be two separate args in the same row. – Bryn Aug 11 '17 at 06:58
  • @glibdud Thanks for clarifying. Since I'd like to split on white-space(s) - str.split()) should suffice. Having trouble implementing it properly however. – Bryn Aug 11 '17 at 07:11

1 Answers1

1

python test.py --nargs "arg arg2" gives the parser (via sys.argv[1:]) ['--nargs', 'arg arg2']. The parser puts that argument string 'arg arg2' into the args namespace. Because nargs='*' it is put in a list.

So args = parser.parse_args() should produce

Namespace(nargs = ['arg arg2'])

python test.py --nargs "arg" "arg2" is different only in that the shell splits the 2 strings, ['--nargs', 'arg'. 'arg2'], and the parser puts both into that list.

It often helps to print sys.argv to see what the parser has to work with.

To get ['arg'] ['arg2'] I think you'd have to use

parser.add_argument('--nargs', nargs='*', action='append')

and

python test.py --nargs "arg" --nargs "arg2"

With that each --nargs occurrence creates a list (because of the *) of its arguments, and appends that to Namespace attribute. Actually it would produce a list of lists:

[['arg'], ['arg2']]
hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • Thanks. I don't want a list of lists though. Seems like str.split()) should suffice. Know how to implement it in parser.add_argument('--nargs', nargs='*') ? – Bryn Aug 11 '17 at 07:14
  • I would just use a list comprehension after parsing. – hpaulj Aug 11 '17 at 07:17