0

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,

1
  • try swapping the add_argument lines and see the change in the response. Commented Oct 30, 2012 at 0:57

2 Answers 2

1

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.

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

Comments

0

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

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.