如何卸载(重新加载)一个Python模块?

我有一个长期运行的Python服务器,并希望能够升级服务,而无需重新启动服务器。什么是最好的方法做这个?

if foo.py has changed:
    unimport foo  <-- How do I do this?
    import foo
    myfoo = foo.Foo()
最佳答案
当模块已经通过使用Python 2中的reload内置函数导入时,可以重新加载模块:

import foo

while True:
    # Do some things.
    if is_changed(foo):
        foo = reload(foo)

在Python 3中,重载被移动到imp模块。在3.4中,imp被弃用,有利于importlib,并且重新加载被添加到后者。当定位3或更高版本时,在调用重新加载或导入时引用适当的模块。

我认为这是你想要的。像Django的开发服务器这样的Web服务器使用它,这样你可以看到你的代码更改的影响,而不需要重新启动服务器进程本身。

引用文档:

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对象。

转载注明原文:如何卸载(重新加载)一个Python模块? - 代码日志