我有一个长期运行的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默认importlib。Reload将只是重新导入作为参数传递的库。它不会重新加载库导入的库。如果您更改了很多文件,并且有一个有点复杂的包要导入,那么您必须进行深度重载。
如果你安装了IPython或Jupyter,你可以使用一个函数来深度重载所有库:
from IPython.lib.deepreload import reload as dreload
dreload(foo)
如果你没有Jupyter,在你的shell中使用以下命令安装它:
pip3 install jupyter
其他回答
如果一个模块不是纯Python的,那么删除它会特别困难。
下面是来自:如何真正删除导入的模块?
您可以使用sys.getrefcount()来找出的实际数量 参考文献
>>> import sys, empty, os
>>> sys.getrefcount(sys)
9
>>> sys.getrefcount(os)
6
>>> sys.getrefcount(empty)
3
大于3的数字表示 它将很难摆脱 模块。本土的“空” (不包含任何内容)模块应该 垃圾收集后
>>> del sys.modules["empty"]
>>> del empty
因为第三个参考是一个人工制品 getrefcount()函数的。
另一种方法是在函数中导入模块。这样,当函数完成时,模块就会被垃圾收集。
在Python 3.0-3.3中,您将使用:
BDFL已经回答了这个问题。
然而,imp在3.4中被弃用了,取而代之的是importlib(谢谢@Stefan!)
因此,我认为您现在应该使用importlib.reload(module),尽管我不确定。
你可以使用importlib.reload()重新加载一个已经被导入的模块:
from importlib import reload # Python 3.4+
import foo
while True:
# Do some things.
if is_changed(foo):
foo = reload(foo)
在Python 2中,重载是内置的。在Python 3中,它被移动到imp模块。在3.4中,弃用了imp,改用了importlib。当目标为3或更高版本时,在调用reload或import时引用适当的模块。
我觉得这就是你想要的。像Django的开发服务器这样的Web服务器使用了这个功能,这样你就可以在不重启服务器进程的情况下看到代码更改的效果。
引用文件中的内容:
Python module’s code is recompiled and the module-level code re-executed, defining a new set of objects which are bound to names in the module’s dictionary by reusing the loader which originally loaded the module. The init function of extension modules is not called a second time. As with all other objects in Python the old objects are only reclaimed after their reference counts drop to zero. The names in the module namespace are updated to point to any new or changed objects. Other references to the old objects (such as names external to the module) are not rebound to refer to the new objects and must be updated in each namespace where they occur if that is desired.
正如您在问题中所指出的,如果Foo类驻留在Foo模块中,则必须重新构造Foo对象。
使用python3并从importlib重新加载的人。
如果你有问题,比如模块似乎没有重新加载…这是因为它需要一些时间重新编译pyc(最多60秒)。我写这个提示只是想让你知道你是否经历过这种问题。