Import and execfile()

George Sakkis george.sakkis at gmail.com
Sat Jan 12 00:16:25 EST 2008


On Jan 11, 6:54 pm, Mitko Haralanov <mi... at qlogic.com> wrote:

> On Fri, 11 Jan 2008 14:05:11 -0800 (PST)
>
> George Sakkis <george.sak... at gmail.com> wrote:
> > # trying to set the configuration:
> > CFG = {}
> > execfile('path/to/some_config.py', CFG)
>
> > Traceback (most recent call last):
> > ...
> > ImportError: No module named master_config
>
> > I understand why this fails but I'm not sure how to tell execfile() to
> > set the path accordingly. Any ideas ?
>
> This might be overly simplistic but you could have a load_config
> function which takes the path to the config file and the variable where
> to load the config as arguments.
>
> In the load_config function, you could get the directory part of the
> config file path, appending it to sys.path, load the config, and then
> remove the newly added directory from sys.path.

Thanks, that's basically what I did eventually and it works for my
simple requirements. Another alternative would be to require the
config files to be modules already in the path. In this case setConfig
becomes almost trivial using __import__ instead of execfile():

import inspect
def setConfig(configfile):
    return dict(inspect.getmembers(__import__(configfile,
fromlist=True)))

On the downside, the config files cannot be moved around as easily as
with execfile. Also, if placed in directories that are not in the
path, one or more ancestor directories may have to be populated with
(empty) __init__.py files to denote them as Python packages. So
generally speaking, when should execfile be preferred to __import__,
or the other way around ?

George



More information about the Python-list mailing list