load python code at runtime load python code at runtime python python

load python code at runtime


As written in the python official documentation, if you just want to import a module by name, you can look it up in the sys.modules dictionary after using __import__.

Supposing your configuration is in myproject.mymodule, you would do like that :

module_name = 'myproject.mymodule'import sys__import__(module_name)mymodule = sys.modules[module_name]# Then you can just access your variables and functionsprint mymodule.var1print mymodule.var2# etc...

You can also use the return value of __import__ statement but you will have to understand fully how python works with namespaces and scopes.


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 bar.py and looks like this:

x = 3y = 4def 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 3bar 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.


To access another Python module, you import it. execfile has been mentioned by a couple people, but it is messy and dangerous. execfile clutters your namespace, possibly even messing up the code you are running. When you want to access another Python source file, use the import statement.

Even better would be not to use a Python file for configuration at all, but rather to use the builtin module ConfigParser or a serialization format like JSON. This way your configuration files don't allow execution of arbitrary (possibly malicious) code, doesn't require people to know Python to configure your program, and can easily be altered programatically.