parsing a dictionary from file in python using argparse?
<p>I have been using a file containing variables as input for a program, which is then imported into the main program at runtime.  I am moving this system to using argparse reading the input values from a file. One of the current input variables is a list of dictionaries, with each dictionary providing settings for a given calculation. </p>

<pre><code>CalculationVals=[{'startx':0,'starty':0,'endx':10, 'endy':10}, {'startx':1,'starty':1,'endx':12, 'endy':12}]
</code></pre>

<p>and then in the main part of the program, the individual CalculationVals are looped over.  Is there a way to read this using argparse, or a better way to provide this input using an argparse method?  Not relying on additional packages is advantageous here.</p>

<p>As Dmitry Suggested, passing json as an argument to function is not a recommended way. </p>

<p>So, I would suggest you to pass json file path in argument instead whole json file.</p>

<pre><code># test_prog.py
import argparse
import json

parser = argparse.ArgumentParser()
parser.add_argument("-f","--filepath", help="json file path")
args = parser.parse_args()

with open(args.filepath, 'r') as f:
      config = json.load(f)

print config
</code></pre>

<p>Then use this value to read using json lib.</p>

<p>In case if json file is remote also, you can pass url as parameter!</p>

<p>Sample run:</p>

<pre><code>$ python test_prog.py -f ./f1.json
[{u'endy': 10, u'endx': 10, u'startx': 0, u'starty': 0}, {u'endy': 12, u'endx': 12, u'startx': 1, u'starty': 1}]
</code></pre>

<p>Content of file, f1.json:</p>

<pre><code>[{"startx":0,"starty":0,"endx":10, "endy":10},{"startx":1,"starty":1,"endx":12, "endy":12}]
</code></pre>

python argparse