简体   繁体   中英

python argparse: how to access arguments

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

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 .

Or use:

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

Output:

'name'

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

Output:

'aixbuildhost'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM