如何动态导入变动模块?

2024-10-01 00:17:02 发布

您现在位置:Python中文网/ 问答频道 /正文

步骤1:假设这是一个变更模块,名为test_模块.py

#coding=utf8
# changing module    

class hello(object):
    pass


"""
class world(object):
    pass
"""

步骤2:动态重新加载changing module,名为dynamis\u changing_导入.py

^{pr2}$

第三步:在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']

谢谢。在


Tags: nameintestimportpackagehellodocdir
1条回答
网友
1楼 · 发布于 2024-10-01 00:17:02

不要搞乱sys.modules。这是一个非常低级的细节。在

要安全地重新加载模块,您只需:

  • 调用python2中的^{}内置函数
  • 在python3.x上使用^{},0<;=x<;4
  • 在python3.4+中使用^{}

对于跨版本解决方案,只需执行以下操作:

import sys
if sys.version_info.major == 3:
    if sys.version_info.minor < 4:
        from imp import reload
    else:
        from importlib import reload

当您想重新导入模块X时,只需执行以下操作:

^{pr2}$

因此,“动态导入”变成:

import moduleX

当您需要重新加载模块时,您只需执行以下操作:

reload(moduleX)

样本运行:

$ echo 'def f():print("a")
> f()' > t.py
$ python2
>>> import t
a
>>> t.f()
a
# in an other shell:
# $ echo 'def f():print("b")
# > f()' > t.py
>>> reload(t)
b
>>> t.f()
b

相关问题 更多 >