Pawankumar Dubey
Pawankumar Dubey

Reputation: 387

Running Python config content in loop

I have an auto generated file which has data in format Config.py

abc = {'Id':894, 'list':4, 'visibleCtx':60}
pqr = {'Id':84, 'list':3, 'visibleCtx':01}
xyz = {'Id':94, 'list':2, 'visibleCtx':10}
...
..
.

I want to loop through the contents of this config file like

while True:
    graphicalUI.setGraphsCtx(Config.(list_in_configFile))

But I am unable to see how this could be done? I have tried RegEx to split each new line based on "=" and run it.

But can we do it with some other smoother way?

Upvotes: 1

Views: 438

Answers (2)

Ajurna
Ajurna

Reputation: 561

if the file is a valid python file why not import it as is and use the values.

also you could take a look after importing the file using the magic method __dict__ https://docs.python.org/2/library/stdtypes.html#object.dict

another option would be to use another format like config file https://docs.python.org/2/library/configparser.html or json https://docs.python.org/2/library/json.html or yaml http://pyyaml.org/. these all create objects which you can iterate over

Upvotes: 1

salezica
salezica

Reputation: 77129

import the file as a module, and run dir() on the module object to obtain its variables.

You can also filter out the special __ variables using a comprehension:

import module
var_names = [v for v in dir(module) if not v.startswith("__")]

Filter any other variables that have no interest. Once you have that, you can get the actual values:

config = { name: getattr(module, name) for name in var_names } 

Upvotes: 1

Related Questions