dynamic module import?
Eduardo Lenz
lenz at joinville.udesc.br
Sat Jan 17 00:34:01 EST 2009
On Friday 16 January 2009 15:03:51 Lawson Hanson wrote:
> 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
> --
> http://mail.python.org/mailman/listinfo/python-list
modu = "os"
exec("from " + modu + " import *")
[]'s
Lenz.
--
Eduardo Lenz Cardoso
Dr. Eng.
Associate Professor
State University of Santa Catarina
Department of Mechanical Engineering
89223-100 - Joinville-SC - Brasil
Tel: +55 47 4009-7971 - Fax: +55 47 4009-7940
E-mail: lenz at Joinville.udesc.br
---------------------------------------------
--
Esta mensagem foi verificada pelo sistema de antivírus e
acredita-se estar livre de perigo.
More information about the Python-list
mailing list