Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type=dict in argparse.add_argument()

I'm trying to set up a dictionary as optional argument (using argparse); the following line is what I have so far:

parser.add_argument('-i','--image', type=dict, help='Generate an image map from the input file (syntax: {\'name\': <name>, \'voids\': \'#08080808\', \'0\': \'#00ff00ff\', \'100%%\': \'#ff00ff00\'}).') 

But running the script:

 $ ./script.py -i {'name': 'img.png','voids': '#00ff00ff','0': '#ff00ff00','100%': '#f80654ff'}  script.py: error: argument -i/--image: invalid dict value: '{name:' 

Even though, inside the interpreter,

>>> a={'name': 'img.png','voids': '#00ff00ff','0': '#ff00ff00','100%': '#f80654ff'} 

works just fine.

So how should I pass the argument instead? Thanks in advance.

like image 889
user975296 Avatar asked Oct 02 '11 10:10

user975296


People also ask

What is Add_argument in Python?

add_argument('indir', type=str, help='Input dir for videos') created a positional argument. For positional arguments to a Python function, the order matters. The first value passed from the command line becomes the first positional argument. The second value passed becomes the second positional argument.

What is dest in parser Add_argument?

Explanation. The dest attribute of a positional argument equals the first argument given to the add_argument() function. An optional argument's dest attribute equals the first long option string without -- . Any subsequent - in the long option string is converted to _ .

How do you add an optional argument in Argparse?

Optional Arguments To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.

How do you pass arguments to Argparse Python?

Create a new ArgumentParser object. All parameters should be passed as keyword arguments. Each parameter has its own more detailed description below, but in short they are: prog - The name of the program (default: os.path.basename(sys.argv[0]) )


1 Answers

Necroing this: json.loads works here, too. It doesn't seem too dirty.

import json import argparse  test = '{"name": "img.png","voids": "#00ff00ff","0": "#ff00ff00","100%": "#f80654ff"}'  parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', type=json.loads)  args = parser.parse_args(['-i', test])  print(args.input) 

Returns:

{u'0': u'#ff00ff00', u'100%': u'#f80654ff', u'voids': u'#00ff00ff', u'name': u'img.png'}

like image 135
Edd Avatar answered Oct 05 '22 13:10

Edd