kkoen
kkoen

Reputation: 13

How to use argsparse to access part of a config file in python?

I have this config.py file:

# config.py 

maria = dict(
    corners = [1,2,3,4],
    area = 2100
)

john = dict(
        corners = [5,6,7,8],
        area = 2400 
    )

and want to use parameters from it by running my main program using argsparse. somewhat like this:

# main.py

import config
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("user", help="maria or john")
args = parser.parse_args()
print(args.user)
print(config.args.user['corners'])

when I run:

pyhton3 main.py maria

I get syntax error on the 2nd print, where I would like to get [1,2,3,4]. How can I use the argument from argparse as an attribute to access the appropriate data in the config file?

Upvotes: 1

Views: 80

Answers (3)

chepner
chepner

Reputation: 532003

Avoid using executable Python code for configuration. Use something like JSON:

config.json would look like

{
    "maria": {
        "corners": [1,2,3,4],
        "area": 2100
    },
    "john": {
        "corners": [5,6,7,8],
        "area": 2400
    }
}

And your script would use

# main.py

import json
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("user", help="maria or john")
args = parser.parse_args()
with open("config.json") as f:
    config = json.load(f)

print(args.user)
print(config[args.user]['corners'])

Upvotes: 1

Tomerikoo
Tomerikoo

Reputation: 19432

One way to go around this is to wrap your parameters in one general dict:

# config.py

params = {'maria': {'corners': [1,2,3,4], 'area': 2100},
          'john':  {'corners': [5,6,7,8], 'area': 2400}}

And then you can simply do in main.py:

print(config.params[args.user]['corners'])

Upvotes: 0

Shubham Sharma
Shubham Sharma

Reputation: 71687

IIUC: You can use the getattr built in function in python.

The getattr(object, name[, default]):

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not >exist, default is returned if provided, otherwise AttributeError is raised.

Replace:

print (config.args.user['corners'])

With:

print(getattr(config, args.user)["corners"])

Upvotes: 2

Related Questions