步骤1:假设这是一个变更模块,名为test_模块.py:
#coding=utf8
# changing module
class hello(object):
pass
"""
class world(object):
pass
"""
步骤2:动态重新加载changing module
,名为dynamis\u changing_导入.py:
第三步:在ipython中测试
然后我发现sys.modules['test_module']
raise key error,这意味着我可以重新导入test\u模块
但我仍然可以dir(test_module)
。。。在
In [1]: import test_module
In [2]: dir(test_module)
Out[2]: ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'hello']
In [3]: import dynamis_changing_import
In [4]: dynamis_changing_import.dy_import('test_module')
1
2
In [5]: import sys
In [6]: sys.modules['test_module'] # Here, test_module does not exist.
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-6-d2451de5c425> in <module>()
----> 1 sys.modules['test_module']
KeyError: 'test_module'
In [7]: dir(test_module) # But... dir... is still there...
Out[7]: ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'hello']
第4步。仍然测试ipython:
我取消了文件dynamis_changing_import.py
中最后两个语句的注释
importlib.import_module(name, package)
print '3'
并且importlib.import_module
没有效果,我重新启动ipython:
In [1]: import sys
In [2]: import dynamis_changing_import
In [3]: import test_module
In [4]: dir(test_module)
Out[4]: ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'hello']
In [5]: # Uncomment the method `world` in test_module
In [6]: dynamis_changing_import.dy_import('test_module')
1
2
3
In [7]: dir(test_module)
Out[7]: ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'hello']
谢谢。在
不要搞乱
sys.modules
。这是一个非常低级的细节。在要安全地重新加载模块,您只需:
对于跨版本解决方案,只需执行以下操作:
当您想重新导入模块
^{pr2}$X
时,只需执行以下操作:因此,“动态导入”变成:
当您需要重新加载模块时,您只需执行以下操作:
样本运行:
相关问题 更多 >
编程相关推荐