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>First option would be to pass in the arguments directly, and call the script once for each set of values.  It's unclear if that meets your use case.</p>

<pre><code>./your_script.py startx=0, starty=0, endx=10, endy=10
</code></pre>

<p>Alternatively, you could use an easily parseable file format such as JSON or CFG, instead of directly importing a python file.  </p>

<p>JSON File:</p>

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

<p>Python:</p>

<pre><code>import argparse
import json

parser = argparse.ArgumentParser()
parser.add_argument('file')
args = parser.parse_args()

with open(args.file) as fi:
        configs = json.load(fi)
        for values in configs['CalculationVals']:
                startx = values['startx']
                starty = values['starty']
</code></pre>

<p>Call the script:
    ./your_script.py config.json</p>

python argparse