Shahbaz Shahbaz - 10 months ago 70
Python Question

load python code at runtime

I would like to load a

file at runtime. This
file is basically a config file with the following format:

predicate_function=func line : <return true or false>

Once this file is loaded, I would like to be able to access
. For each line, I'll pass it to the predicate function, and if it returns false, I'll ignore it.

In any case, I'm not sure how to load a python file at runtime and access its variables.

Clarification: there may be any number of these config files that I need to pass to the main program and I won't know their names until runtime. Google tells me I should use
. I'm not sure how to correctly use that method and then access the variables of the imported file.

Answer Source

You just need to be able to dynamically specify the imports and then dynamically get at the variables.

Let's say your config file is and looks like this:

x = 3
y = 4
def f(x): return (x<4)

Then your code should look like this:

import sys

# somehow modnames should be a list of strings that are the names of config files
# you can do this more dynamically depending on what you're doing                                                                                                     
modnames = ['bar']

for modname in modnames:
  exec('import %s' % modname)

for modname in modnames:
  mod = sys.modules[modname]
  for k in mod.__dict__:
    if k[:2] != '__':
      print modname, k, mod.__dict__[k]

I get this output:

bar f <function f at 0x7f2354eb4cf8>
bar x 3
bar y 4

Then you at least have all the variables and functions. I didn't quite get what you wanted from the predicate functions, but maybe you can get that on your own now.