我有一个长期运行的Python服务器,希望能够在不重新启动服务器的情况下升级服务。最好的方法是什么?
if foo.py has changed:
unimport foo <-- How do I do this?
import foo
myfoo = foo.Foo()
我有一个长期运行的Python服务器,希望能够在不重新启动服务器的情况下升级服务。最好的方法是什么?
if foo.py has changed:
unimport foo <-- How do I do this?
import foo
myfoo = foo.Foo()
当前回答
对于Python 2,使用内置函数reload:
reload(module)
对于Python 2和Python 3.2-3.3,使用reload from module imp:
import imp
imp.reload(module)
对于Python≥3.4,imp已弃用,改用importlib,因此使用以下命令:
import importlib
importlib.reload(module)
or:
from importlib import reload
reload(module)
TL; diana:
Python≥3.4:importlib.reload(module) Python 3.2 - 3.3: imp.reload(module) Python 2: reload(module)
其他回答
在Python 3.0-3.3中,您将使用:
BDFL已经回答了这个问题。
然而,imp在3.4中被弃用了,取而代之的是importlib(谢谢@Stefan!)
因此,我认为您现在应该使用importlib.reload(module),尽管我不确定。
Enthought Traits有一个模块很好地解决了这个问题。https://traits.readthedocs.org/en/4.3.0/_modules/traits/util/refresh.html
它将重新加载任何已更改的模块,并更新正在使用它的其他模块和实例对象。它在__very_private__方法的大多数时候都不起作用,并且可能会阻塞类继承,但它为我节省了大量的时间,使我不必在编写PyQt gui或在Maya或Nuke等程序中运行的东西时重新启动主机应用程序。它可能有20% - 30%的时间不起作用,但它仍然非常有帮助。
Enthought的包不会在文件更改时重新加载它们——您必须显式地调用它——但如果您确实需要它,实现它应该不是那么困难
从sys. exe中移除模块。modules也需要删除'None'类型。
方法1:
import sys
import json ## your module
for mod in [ m for m in sys.modules if m.lstrip('_').startswith('json') or sys.modules[m] == None ]: del sys.modules[mod]
print( json.dumps( [1] ) ) ## test if functionality has been removed
方法2,使用簿记条目,删除所有依赖项:
import sys
before_import = [mod for mod in sys.modules]
import json ## your module
after_import = [mod for mod in sys.modules if mod not in before_import]
for mod in [m for m in sys.modules if m in after_import or sys.modules[m] == None]: del sys.modules[mod]
print( json.dumps( [2] ) ) ## test if functionality has been removed
可选的,只是为了确保所有的条目都出来了,如果你这样选择:
import gc
gc.collect()
其他选项。请参阅Python默认importlib。Reload将只是重新导入作为参数传递的库。它不会重新加载库导入的库。如果您更改了很多文件,并且有一个有点复杂的包要导入,那么您必须进行深度重载。
如果你安装了IPython或Jupyter,你可以使用一个函数来深度重载所有库:
from IPython.lib.deepreload import reload as dreload
dreload(foo)
如果你没有Jupyter,在你的shell中使用以下命令安装它:
pip3 install jupyter
对于Python 2,使用内置函数reload:
reload(module)
对于Python 2和Python 3.2-3.3,使用reload from module imp:
import imp
imp.reload(module)
对于Python≥3.4,imp已弃用,改用importlib,因此使用以下命令:
import importlib
importlib.reload(module)
or:
from importlib import reload
reload(module)
TL; diana:
Python≥3.4:importlib.reload(module) Python 3.2 - 3.3: imp.reload(module) Python 2: reload(module)