在python中创建和导入动态模块

时间:2018-02-21 08:02:05

标签: python

我正在尝试动态创建和导入包含单个变量x

的模块

CreateImportDynModule.py

import sys
from types import ModuleType

print "1 --> __name__: ", __name__

dm = ModuleType(__name__) #create module with same name
dm.x = 5                  #add member x = 5

print "2 --> __name__: ", __name__
print "3 -->", sys.modules[__name__]

sys.modules[__name__] = dm  #replace this module with dm
                            #which have same name
                            ### Running CreateImportDynModuleDemo.py failes
                            #In debug, I realize that this screws
                            #__name__, setting it to NoneType
print "4 --> __name__: ", __name__
print "5 -->", sys.modules[__name__]
print "6 -->", sys.modules[__name__].x  

CreateImportDynModuleDemo.py

import CreateImportDynModule as cidm
#print cidm.x  #I want this to work, but above import itself does not work and 
               #gives error stated below

运行CreateImportDynModule.py会得到以下正确的输出:

1 --> __name__:  __main__
2 --> __name__:  __main__
3 --> <module '__main__' from 'path/CreateImportDynModule.py'>
4 --> __name__:  __main__
5 --> <module '__main__' (built-in)>
6 --> 5

但是,运行CreateImportDynModuleDemo.py会出现以下错误:

1 --> __name__:  CreateImportDynModule
2 --> __name__:  CreateImportDynModule
3 --> <module 'CreateImportDynModule' from 'path/CreateImportDynModule.py'>
4 --> __name__:  None
5 -->Traceback (most recent call last):

  File "path/CreateImportDynModuleDemo.py", line 10, in <module>
    import CreateImportDynModule as cidm
  File "path/CreateImportDynModule.py", line 18, in <module>
    print "5 -->", sys.modules[__name__]
AttributeError: 'NoneType' object has no attribute 'modules'

sys.modules[__name__] = dm__name__设置为NoneType,因为您可以在三个哈希###中读取CreateImportDynModule.py的注释。 但为什么会这样呢?

0 个答案:

没有答案