如何卸载(重新加载)Python 模块? [英] How do I unload (reload) a Python module?
问题描述
我有一个长期运行的 Python 服务器,并且希望能够在不重新启动服务器的情况下升级服务.这样做的最佳方法是什么?
I have a long-running Python server and would like to be able to upgrade a service without restarting the server. What's the best way do do this?
if foo.py has changed:
unimport foo <-- How do I do this?
import foo
myfoo = foo.Foo()
推荐答案
您可以使用 reload
内置函数(仅限 Python 3.4+):
from importlib import reload
import foo
while True:
# Do some things.
if is_changed(foo):
foo = reload(foo)
在 Python 3 中,reload
已移至 imp
模块.在 3.4 中,imp
被弃用,取而代之的是 importlib
和 reload
被添加到后者.面向 3 或更高版本时,请在调用 reload
时引用适当的模块或导入它.
In Python 3, reload
was moved to the imp
module. In 3.4, imp
was deprecated in favor of importlib
, and reload
was added to the latter. When targeting 3 or later, either reference the appropriate module when calling reload
or import it.
我认为这就是您想要的.像 Django 的开发服务器这样的 Web 服务器使用它,这样您就可以看到代码更改的效果,而无需重新启动服务器进程本身.
I think that this is what you want. Web servers like Django's development server use this so that you can see the effects of your code changes without restarting the server process itself.
引用文档:
Python 模块的代码被重新编译并重新执行模块级代码,定义一组新的对象绑定到模块中的名称字典.初始化函数扩展模块不称为第二次.与所有其他对象一样在 Python 中,旧对象只是在引用计数后回收降为零.模块中的名称命名空间被更新为指向任何新的或改变的对象.其他对旧对象的引用(例如模块外部的名称)不是反弹以引用新对象并且必须在每个命名空间中更新如果需要,它们会出现在哪里.
Python modules’ code is recompiled and the module-level code reexecuted, defining a new set of objects which are bound to names in the module’s dictionary. 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
对象.
As you noted in your question, you'll have to reconstruct Foo
objects if the Foo
class resides in the foo
module.
这篇关于如何卸载(重新加载)Python 模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!