我有一个长期运行的Python服务器,希望能够在不重新启动服务器的情况下升级服务。最好的方法是什么?

if foo.py has changed:
    unimport foo  <-- How do I do this?
    import foo
    myfoo = foo.Foo()

当前回答

这是重新加载一个模块的现代方式:

from importlib import reload

如果你想支持3.5以上的Python版本,请使用以下命令:

from sys import version_info
if version_info[0] < 3:
    pass # Python 2 has built in reload
elif version_info[0] == 3 and version_info[1] <= 4:
    from imp import reload # Python 3.0 - 3.4 
else:
    from importlib import reload # Python 3.5+

这定义了一个重载方法,可以通过模块调用来重载它。例如,reload(math)将重载数学模块。

其他回答

Enthought Traits有一个模块很好地解决了这个问题。https://traits.readthedocs.org/en/4.3.0/_modules/traits/util/refresh.html

它将重新加载任何已更改的模块,并更新正在使用它的其他模块和实例对象。它在__very_private__方法的大多数时候都不起作用,并且可能会阻塞类继承,但它为我节省了大量的时间,使我不必在编写PyQt gui或在Maya或Nuke等程序中运行的东西时重新启动主机应用程序。它可能有20% - 30%的时间不起作用,但它仍然非常有帮助。

Enthought的包不会在文件更改时重新加载它们——您必须显式地调用它——但如果您确实需要它,实现它应该不是那么困难

下面的代码允许你兼容Python 2/3:

try:
    reload
except NameError:
    # Python 3
    from imp import reload

你可以在两个版本中使用它作为reload(),这让事情变得更简单。

Python不会在重载时重新计算子模块地址,如果它在sys.modules中

这里有一个变通办法,虽然不完美,但有效。

# Created by BaiJiFeiLong@gmail.com at 2022/2/19 18:50
import importlib
import types

import urllib.parse
import urllib.request


def reloadModuleWithChildren(mod):
    mod = importlib.reload(mod)
    for k, v in mod.__dict__.items():
        if isinstance(v, types.ModuleType):
            setattr(mod, k, importlib.import_module(v.__name__))


fakeParse = types.ModuleType("urllib.parse")
realParse = urllib.parse

urllib.parse = fakeParse
assert urllib.parse is fakeParse

importlib.reload(urllib)
assert urllib.parse is fakeParse
assert getattr(urllib, "parse") is fakeParse

reloadModuleWithChildren(urllib)
assert urllib.parse is not fakeParse
assert urllib.parse is realParse

重新加载(模块),但前提是它是完全独立的。如果其他任何东西引用了该模块(或属于该模块的任何对象),那么您将会得到一些微妙而奇怪的错误,这些错误是由旧代码存在的时间比您预期的要长,并且像isinstance这样的错误在相同代码的不同版本之间无法工作。

如果有单向依赖关系,还必须重新加载依赖于重新加载的模块的所有模块,以消除对旧代码的所有引用。然后递归地重新加载依赖于重新加载模块的模块。

如果你有循环依赖关系,这是非常常见的,例如当你处理重新加载一个包时,你必须一次性卸载组中的所有模块。使用reload()无法做到这一点,因为它会在刷新依赖项之前重新导入每个模块,从而允许旧的引用渗透到新模块中。

在这种情况下,唯一的方法是入侵sys。模块,这是不受支持的。你必须仔细检查并删除每个系统。您希望在下次导入时重新加载的模块项,还可以删除值为None的项,以处理缓存失败的相对导入的实现问题。这并不是很好,但只要你有一个完全自包含的依赖集,并且不会在代码库之外留下引用,它就是可行的。

最好是重新启动服务器。:-)

你可以使用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中,重载是内置的。在Python 3中,它被移动到imp模块。在3.4中,弃用了imp,改用了importlib。当目标为3或更高版本时,在调用reload或import时引用适当的模块。

我觉得这就是你想要的。像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对象。