python - 如何卸载(重新加载)Python 模块?

标签 python module reload python-import

我有一个长期运行的 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 中,它是 movedimp模块。在 3.4 中,impdeprecated赞成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/

相关文章:

python - 使用装饰器向 __all__ 添加名称是一种好习惯吗?

python - 如何在Python中绘制耦合非线性二阶ODE的二阶导数?

python - 模拟 ec2.describe_regions() (AWS) 的代理

javascript - module.exports 返回未定义

powershell - 如何将模块导入到 powershell 中而不等待其完成?

java - Eclipse RCP - 以编程方式更改 plugin.xml?重新加载?

android - 从 DrawerLayout 中刷新 Viewpager

javascript - 返回导航/页面刷新问题

python - TCP多线程服务器

python - 使用点符号导入