Dynamically importing modules

Bjorn Pettersen BPettersen at NAREX.com
Wed Jun 20 14:35:12 EDT 2001


> From: Jared Lee Peterson [mailto:jared at difinium.com]
> 
> I have a quick question about importing modules.  I would 
> like to have a
> script that in sitting in a directory and in this directory I want to
> have sub directories that represent modules to that script.  However
> I do not want this script to have any prior knowledge of what modules
> may exist.  So I would like for the script to look at it 
> current working
> directory and then try to load each module that does exist through the
> use of import.  But I can not seem to figure out how to get import to
> work for me.  Because I need to be able to loop through a list
> (os.listdir()) of the subdirectories/modules that the script has found
> and try to import them.  Does anyone have any suggestions?  Does this
> even make sense?

you can use the __import__ function to import a module based on it's
name (as a string), ie. the following two statements are equivalent:

  mymodule = __import__('mymodule')

and

  import mymodule

-- bjorn




More information about the Python-list mailing list