dynamic module import?

Lawson Hanson lawsonhanson at optusnet.com.au
Sat Jan 17 00:03:51 CET 2009


Is it possible to import a module of Python code
     where I do not know the name of the module
     until run-time?

The Python statement:

     from someModule import *

requires that "someModule" be the name of the module,
     but what I would like is to be able to define a value
     for "someModule" ... and provided that such a module
     exists (in an extended "sys.path" directory), then
     import from the specified module at run-time

If I have a module called "dummy.py" in my own "myModules"
     directory (just below my HOME directory in Linux)

If I do this:

     import os, sys

     myModDir = os.environ["HOME"] + "/myModules"

     sys.path.append(myModDir)

     modName = "%s/%s" % (myModDir, "dummy")

     from modName import *

I get the following error:

     ImportError: No module named modName

So is there any way to get Python to import the named module
     without just doing "from dummy import *", because I will
     not know that the user wants to use the "dummy" module
     until run-time ... I'm trying to import control data
     for different run scenarios which will be defined in
     differently named Python modules which the user will
     specify at run-time with a command-line option

And help with this would be most appreciated

Best regards,

Lawson Hanson
------
     Melbourne, Victoria, Australia



More information about the Python-list mailing list