我有一个长期运行的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)
其他回答
以Abaqus为例,这就是它的工作方式。 假设你的文件是Class_VerticesEdges.py
sys.path.append('D:\...\My Pythons')
if 'Class_VerticesEdges' in sys.modules:
del sys.modules['Class_VerticesEdges']
print 'old module Class_VerticesEdges deleted'
from Class_VerticesEdges import *
reload(sys.modules['Class_VerticesEdges'])
对于像我这样想卸载所有模块的人(当在Emacs下的Python解释器中运行时):
for mod in sys.modules.values():
reload(mod)
更多信息请参见重新加载Python模块。
下面的代码允许你兼容Python 2/3:
try:
reload
except NameError:
# Python 3
from imp import reload
你可以在两个版本中使用它作为reload(),这让事情变得更简单。
从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