Pawankumar Dubey Pawankumar Dubey - 6 months ago 52
Python Question

Running Python config content in loop

I have an auto generated file which has data in format

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:

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?


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 }