我需要完整地在python中重新加載模塊。我的意思是「完全‘的是,我不希望 以下特點(從Python 2.6文檔的內置加載功能):重新加載並重置
’......如果一個模塊的新版本不定義是由舊版本 定義的名稱,舊的定義仍然......「。
即我不希望在新的模塊版本消失要保留舊名稱。
實現此目標的最佳做法是什麼?
謝謝!
我需要完整地在python中重新加載模塊。我的意思是「完全‘的是,我不希望 以下特點(從Python 2.6文檔的內置加載功能):重新加載並重置
’......如果一個模塊的新版本不定義是由舊版本 定義的名稱,舊的定義仍然......「。
即我不希望在新的模塊版本消失要保留舊名稱。
實現此目標的最佳做法是什麼?
謝謝!
刪除從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'
測試與第三方模塊
>>> 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
@frank我有一種感覺,如果模塊本身做一些其他的導入 - 它可能不是特別強大 - 我已經在第三方模塊上做了另一個測試,並且如果你不刪除它似乎不起作用它下面的任何其他模塊(但嗯...) –
爲什麼不用Ctrl + F重新啓動Python Shell?您仍然可以使用ALT + P重新調用先前的命令。 – LarsVegas
@larsvegas:我不在python shell中,我從我的程序動態加載代碼。 – frank
我想你應該看看['gc'](http://docs.python.org/library/gc.html#module-gc)模塊。 – LarsVegas