【问题标题】:reload with reset重新加载并重置
【发布时间】:2012-10-01 08:08:25
【问题描述】:

我需要在 python 中完全重新加载一个模块。我所说的“完全”是我不 想要以下功能(来自内置重载功能的 python 2.6 文档):

"...如果模块的新版本没有定义旧版本定义的名称 版本,旧定义仍然存在......”。

即我不希望保留在新模块版本中消失的旧名称。

实现这一目标的最佳做法是什么?

谢谢!

【问题讨论】:

  • 你为什么不直接用 Ctrl+F 重启你的 Python Shell?您仍然可以使用 ALT+P 重新调用以前的命令。
  • @larsvegas:我不在 python shell 中,我正在从我的程序中动态加载代码。
  • 我想你应该看看gc模块。

标签: python


【解决方案1】:

sys.modules 中删除模块并重新导入可能是一个开始,尽管我没有在以下范围内对其进行测试:

import itertools

itertools.TEST = 7
reload(itertools)
print itertools.TEST
# 7

import sys
del sys.modules['itertools']
import itertools
print itertools.TEST

#Traceback (most recent call last):
#  File "/home/jon/stackoverflow/12669546-reload-with-reset.py", line 10, in <module>
#    print itertools.TEST
# AttributeError: 'module' object has no attribute 'TEST'

使用第 3 方模块进行测试

>>> import pandas
>>> import sys
>>> del sys.modules['pandas']
>>> import pandas
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    import pandas
  File "/usr/local/lib/python2.7/dist-packages/pandas-0.7.3-py2.7-linux-x86_64.egg/pandas/__init__.py", line 10, in <module>
    import pandas._tseries as lib
AttributeError: 'module' object has no attribute '_tseries'
>>> to_del = [m for m in sys.modules if m.startswith('pandas.')]
>>> for td in to_del:
    del sys.modules[td]

>>> import pandas
>>> # now it works

【讨论】:

  • 看起来不错,但这是推荐的方法吗?有什么陷阱吗?
  • @frank 我有一种感觉,如果模块本身进行一些其他导入 - 它可能不是特别健壮 - 我已经对第 3 方模块进行了另一次测试,但似乎没有如果你不删除它下面的任何其他模块(但是嗯......)
猜你喜欢
  • 2020-03-19
  • 1970-01-01
  • 1970-01-01
  • 2021-01-04
  • 1970-01-01
  • 1970-01-01
  • 2014-02-06
  • 2014-02-13
  • 1970-01-01
相关资源
最近更新 更多