Cannot import a module from a variable

Colin J. Williams cjw at sympatico.ca
Sun Oct 15 18:17:21 CEST 2006


Christian Joergensen wrote:
> "Jia Lu" <Roka100 at gmail.com> writes:
> 
>> Hi all:
>>
>> I try to do things below:
>>>>> import sys
>>>>> for i in sys.modules.keys():
>> 	import i
>> Traceback (most recent call last):
>>   File "<pyshell#67>", line 2, in <module>
>>     import i
>> ImportError: No module named i
>>
>> But it seems that import donot know what is i ? why?
> 
> Try using __import__(i) instead.
> 
(a) you need something like exec('import ' + i) for most cases
but (b) "encodings" is a package i.e. it points to a directory which has 
an __init__.py file.

Colin W.




More information about the Python-list mailing list