如何卸载(重新加载)模块? [英] How do I unload (reload) a module?

查看:101
本文介绍了如何卸载(重新加载)模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个运行时间较长的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()

推荐答案

使用在Python 3中,reload已移至 imp 模块.在3.4中,不推荐使用imp,而推荐使用 importlib 和<向后者添加了href ="https://docs.python.org/3.4/library/importlib.html#importlib.reload" rel ="noreferrer"> 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.

要引用文档,请执行以下操作:

To quote from the docs:

Python模块的代码将重新编译并 重新执行模块级代码, 定义一组新的对象 绑定到模块名称中 字典.的init函数 扩展模块不称为 第二次.与所有其他对象一样 在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.

这篇关于如何卸载(重新加载)模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆