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

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

当前回答

对于像我这样想卸载所有模块的人(当在Emacs下的Python解释器中运行时):

   for mod in sys.modules.values():
      reload(mod)

更多信息请参见重新加载Python模块。

其他回答

对于Python 2,使用内置函数reload:

reload(module)

对于Python 2和Python 3.2-3.3,使用reload from module imp:

import imp
imp.reload(module)

对于Python≥3.4,imp已弃用,改用importlib,因此使用以下命令:

import importlib
importlib.reload(module)

or:

from importlib import reload
reload(module)

TL; diana:

Python≥3.4:importlib.reload(module) Python 3.2 - 3.3: imp.reload(module) Python 2: reload(module)

如果你不在服务器上,但正在开发,需要频繁地重新加载一个模块,这里有一个不错的技巧。

首先,确保您使用的是Jupyter Notebook项目中的优秀IPython shell。在安装Jupyter之后,您可以使用ipython或Jupyter控制台启动它,甚至更好的是Jupyter qtconsole,这将为您提供一个在任何操作系统中都具有代码完成功能的漂亮的彩色控制台。

现在在shell中输入:

%load_ext autoreload
%autoreload 2

现在,每次运行脚本时,模块都会被重新加载。

除了2,还有其他自动重载魔法的选项:

%autoreload
Reload all modules (except those excluded by %aimport) automatically now.

%autoreload 0
Disable automatic reloading.

%autoreload 1
Reload all modules imported with %aimport every time before executing the Python code typed.

%autoreload 2
Reload all modules (except those excluded by %aimport) every time before
executing the Python code typed.

当然,它也可以在木星笔记本上工作。

在Python 3.0-3.3中,您将使用:

BDFL已经回答了这个问题。

然而,imp在3.4中被弃用了,取而代之的是importlib(谢谢@Stefan!)

因此,我认为您现在应该使用importlib.reload(module),尽管我不确定。

使用python3并从importlib重新加载的人。

如果你有问题,比如模块似乎没有重新加载…这是因为它需要一些时间重新编译pyc(最多60秒)。我写这个提示只是想让你知道你是否经历过这种问题。

以Abaqus为例,这就是它的工作方式。 假设你的文件是Class_VerticesEdges.py

sys.path.append('D:\...\My Pythons')
if 'Class_VerticesEdges' in sys.modules:  
    del sys.modules['Class_VerticesEdges']
    print 'old module Class_VerticesEdges deleted'
from Class_VerticesEdges import *
reload(sys.modules['Class_VerticesEdges'])