我有一个长期运行的 Python 服务器,并且希望能够在不重新启动服务器的情况下升级服务。这样做的最佳方法是什么?
if foo.py has changed:
unimport foo <-- How do I do this?
import foo
myfoo = foo.Foo()
最佳答案
您可以使用 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 中,reload
是内置的。在 Python 3 中,它是 moved到imp
模块。在 3.4 中,imp
为 deprecated赞成importlib
.面向 3 或更高版本时,在调用 reload
时引用相应的模块或导入它。
我认为这就是你想要的。像 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
对象。
关于python - 如何卸载(重新加载)Python 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/437589/