我有一个长期运行的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/3:
try:
reload
except NameError:
# Python 3
from imp import reload
你可以在两个版本中使用它作为reload(),这让事情变得更简单。
其他回答
如果你不在服务器上,但正在开发,需要频繁地重新加载一个模块,这里有一个不错的技巧。
首先,确保您使用的是Jupyter Notebook项目中的优秀IPython shell。在安装Jupyter之后,您可以使用ipython或Jupyter控制台启动它,甚至更好的是Jupyter qtconsole,这将为您提供一个在任何操作系统中都具有代码完成功能的漂亮的彩色控制台。
现在在shell中输入:
%load_ext autoreload
%autoreload 2
现在,每次运行脚本时,模块都会被重新加载。
除了2,还有其他自动重载魔法的选项:
%autoreload
Reload all modules (except those excluded by %aimport) automatically now.
%autoreload 0
Disable automatic reloading.
%autoreload 1
Reload all modules imported with %aimport every time before executing the Python code typed.
%autoreload 2
Reload all modules (except those excluded by %aimport) every time before
executing the Python code typed.
当然,它也可以在木星笔记本上工作。
使用python3并从importlib重新加载的人。
如果你有问题,比如模块似乎没有重新加载…这是因为它需要一些时间重新编译pyc(最多60秒)。我写这个提示只是想让你知道你是否经历过这种问题。
从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 3.0-3.3中,您将使用:
BDFL已经回答了这个问题。
然而,imp在3.4中被弃用了,取而代之的是importlib(谢谢@Stefan!)
因此,我认为您现在应该使用importlib.reload(module),尽管我不确定。
对于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)