2

it seems this question has been asked before very often, but i cant find the right answer anyway. so here it goes again...

example code: one optional arg, with args converted to dict.

import argparse

epilog = '''usage example:'''

parser = argparse.ArgumentParser(description="add watchit hosts", epilog=epilog)
parser.add_argument('--add', nargs='*', default="-1", metavar="key 'value'")
args = vars(parser.parse_args())
print args
print args['name']

python argparse_test.py --add name 'aixbuildhost' spits out the following:

{'add': ['name', 'aixbuildhost']}
Traceback (most recent call last):
  File "argparse_test.py", line 9, in <module>
    print args['name']
KeyError: 'name'

so the big question is, how to i get the "name'?

2
  • Use args['add'][1] Commented Jul 4, 2018 at 8:51
  • When learning argparse or almost any debugging with it, it's a good idea to look at args without further processing, print(args). That will show you the values AND their names. Commented Jul 4, 2018 at 15:11

2 Answers 2

2

The key is 'add', the value is a list containing two arguments -- name and aixbuildhost. To access the values:

args['add'][0] - will return 'name'

args['add'][1] - will return 'aixbuildhost'

See more on how to use and parse dictionaries here.

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

2 Comments

hmm..this is a little unpleasant, no way to access it like "args['add'][name]" instead of using the index? name is more consistent in case somenone is messing up the argument order.
Why don't you just use --name as an argument and not --add? That way, without using vars() as well, you'll be able to access aixbuildhosts with args.name. In the way you're doing it now, after the argument you give two more arguments, thus a list is used, no way to access them without an index value. Also, if they mess up the argument order you'll just return an error and tell them so, catch such an exception via try/except. If the value of args['add'][0] is not 'name', tell them that they've messed up.
0

Or use:

list(args.values())[0][0]

Output:

'name'

list(args.values())[0][1]

Output:

'aixbuildhost'

Comments

Your Answer

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