Dynamically importing modules in Python3.0?

I want to dynamically import a list of modules. I have a problem with this. Python always screams ImportError

and says my module doesn't exist.

First, I get a list of the module filenames and chop off the suffixes ".py"

, for example:

viable_plugins = filter(is_plugin, os.listdir(plugin_dir))
viable_plugins = map(lambda name: name[:-3], viable_plugins)

      

Then I go os.chdir

to the plugins directory and the map __import__

whole thing, for example:

active_plugins = map(__import__, viable_plugins)

      

However, when I turn active_plugins

into a list and try to access the modules inside, Python will throw an error stating that it cannot import modules as they don't seem to exist.

What am I doing wrong?


Edit: just using an interactive interpreter, execute os.chdir

and __import__(modulefilename)

create exactly what I need. Why doesn't this approach work then? Am I doing something more functional with Python?

+2


source to share


1 answer


It says that it cannot do this because even if you change your directory where the modules are located, that directory is not in the import path.

What you need to do, instead of going to the directory where the modules are located, is to paste that directory into sys.path

.



import sys
sys.path.insert(0, directory_of_modules)
# do imports here.

      

+7


source







All Articles