Finger twist
Finger twist

Reputation: 3786

adding argument with argparse

I have this little problem with argparse :

#!/usr/bin/python2.6
#test.py
import argparse

parser = argparse.ArgumentParser(description="test")
parser.add_argument('c', nargs='*')
parser.add_argument('cj', nargs='*')

results = vars(parser.parse_args())
print results

Now in the command line if I type in : "test.py c 1"

it returns this

{'cj': [], 'c': ['c', '1']}

but if I type in " "test.py cj 1"

it returns this :

{'cj': [], 'c': ['cj', '1']}

I am expecting the second example to return value in the 'cj' key, but it keeps on appears in the 'c' key.

what am I doing wrong ?

cheers,

Upvotes: 0

Views: 117

Answers (2)

jfs
jfs

Reputation: 414275

There are at least two issues:

  • you use positional arguments (they do not start with '-', or '--'), but you provide their names at command line
  • you use nargs='*' that consumes all arguments that it can

Upvotes: 0

Nathan Villaescusa
Nathan Villaescusa

Reputation: 17629

Your issue is that the * will match everything that comes after it. Since the c argument has the first * everything that is passed in will end up in c.

If you want to store a single item in cj and a single item in c you could do:

parser = argparse.ArgumentParser(description="test")
parser.add_argument('c', nargs='+')
parser.add_argument('cj', nargs='+')

If what you want is:

{'cj': ['1'], 'c': ['cj']}

This is because the + matches a single argument.

Upvotes: 1

Related Questions