Bryn
Bryn

Reputation: 257

Python argparse - using quotes

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']

Upvotes: 0

Views: 3985

Answers (1)

hpaulj
hpaulj

Reputation: 231385

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']]

Upvotes: 1

Related Questions