3

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?

SilentGhost
322k67 gold badges312 silver badges294 bronze badges
asked Oct 11, 2009 at 16:17

1 Answer 1

8

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.
answered Oct 11, 2009 at 16:21
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.