views:

162

answers:

1

I want to dynamically import a list of modules. I'm having a problem doing this. Python always yells out an ImportError and tells me my module doesn't exist.

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

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

Then I os.chdir to the plugins directory and map __import__ the entire thing, like so:

active_plugins = map(__import__, viable_plugins)

However, when I turn active_plugins into a list and try to access the modules within, Python will throw out an error, saying it cannot import the modules since they don't appear to be there.

What am I doing wrong?


Edit: By simply using the interactive interpreter, doing os.chdir and __import__(modulefilename) produces exactly what I need. Why isn't the above approach working, then? Am I doing something wrong with Python's more functional parts?

+5  A: 

It says it can't do it, because even though you're changing your directory to where the modules are, that directory isn't on your import path.

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

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