Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Importing a module using a variable name

Status
Not open for further replies.

Winstonb

Technical User
Aug 11, 2001
29
GB
Hello,

I would like to import a module using a "read in" variable.
eg, something along the lines of:

----------------------------------------------------------
variable = raw_input("Module name is: ") # type in MYMOD
import variable
----------------------------------------------------------

The import command however doesn't expand "variable" to "MYMOD".

ie, ImportError: no module named variable

Does anyone know any way round this ?



 
Dangerous, but if you must:

The file t.py contains:

Code:
variable = raw_input("Module name is:  ") 
exec("import " + variable)

The file t2.py contains:
Code:
print "Hello."

[tt]$ python t.py
Module name is: t2
Hello.


[/tt]
 
Thanks ZaSter,
That worker perfectly.

Winston
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top