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?
我有一个长时间运行的Python服务器,希望能够在不重新启动服务器的情况下升级服务。最好的方法是什么?
if foo.py has changed:
unimport foo <-- How do I do this?
import foo
myfoo = foo.Foo()
16 个解决方案
#1
527
You can reload a module when it has already been imported by using the reload
builtin function in Python 2:
当使用Python 2中的reload builtin函数导入时,您可以重新加载模块。
import foo
while True:
# Do some things.
if is_changed(foo):
foo = reload(foo)
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.
在Python 3中,reload被移动到imp模块。在3.4中,imp被弃用,支持importlib,并将reload添加到后者。当目标3或更高时,在调用reload或导入时引用适当的模块。
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.
我认为这就是你想要的。像Django的开发服务器这样的Web服务器使用它,这样您就可以看到代码更改的效果,而无需重新启动服务器进程本身。
To quote from the docs:
引用文件:
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.
Python模块的代码被重新编译,模块级代码被重新执行,定义了一组新的对象,这些对象绑定到模块字典中的名称。扩展模块的init功能不是第二次调用。与Python中的所有其他对象一样,旧对象只有在引用计数降为零之后才被回收。模块名称空间中的名称更新为指向任何新的或已更改的对象。其他对旧对象的引用(比如模块外部的名称)不会被反弹来引用新对象,并且必须在每个名称空间中进行更新,如果需要的话。
As you noted in your question, you'll have to reconstruct Foo
objects if the Foo
class resides in the foo
module.
正如您在问题中提到的,如果Foo类驻留在Foo模块中,就必须重新构造Foo对象。
#2
217
In Python 3.0–3.3 you would use: imp.reload(module)
在Python 3.0-3.3中,您将使用:impl .reload(模块)
The BDFL has answered this question.
BDFL回答了这个问题。
However, imp
was deprecated in 3.4, in favour of importlib
(thanks @Stefan!).
然而,imp在3.4中被弃用,转而支持importlib(感谢@Stefan!)
I think, therefore, you’d now use importlib.reload(module)
, although I’m not sure.
因此,我认为您现在使用importlib.reload(模块),尽管我不确定。
#3
72
It can be especially difficult to delete a module if it is not pure Python.
如果一个模块不是纯Python,那么删除它就特别困难。
Here is some information from: How do I really delete an imported module?
这里有一些信息:如何真正删除导入的模块?
You can use sys.getrefcount() to find out the actual number of references.
您可以使用sys.getrefcount()来查找实际引用的数量。
>>> import sys, empty, os
>>> sys.getrefcount(sys)
9
>>> sys.getrefcount(os)
6
>>> sys.getrefcount(empty)
3
Numbers greater than 3 indicate that it will be hard to get rid of the module. The homegrown "empty" (containing nothing) module should be garbage collected after
大于3的数字表明很难去掉模块。本地的“空”(不包含任何)模块应该被垃圾回收。
>>> del sys.modules["empty"]
>>> del empty
as the third reference is an artifact of the getrefcount() function.
因为第三个引用是getrefcount()函数的一个工件。
#4
54
reload(module)
, but only if it's completely stand-alone. If anything else has a reference to the module (or any object belonging to the module), then you'll get subtle and curious errors caused by the old code hanging around longer than you expected, and things like isinstance
not working across different versions of the same code.
reload(模块),但必须完全独立。如果对模块(或模块的任何对象)有任何引用,那么您将会得到一些由旧代码所导致的微妙的、奇怪的错误,这些错误会比您预期的时间长一些,比如isinstance没有在相同代码的不同版本中工作。
If you have one-way dependencies, you must also reload all modules that depend on the the reloaded module to get rid of all the references to the old code. And then reload modules that depend on the reloaded modules, recursively.
如果有单向依赖关系,则还必须重新加载依赖于重新加载模块的所有模块,以消除对旧代码的所有引用。然后重新加载依赖于重新加载模块的模块,递归地进行。
If you have circular dependencies, which is very common for example when you are dealing with reloading a package, you must unload all the modules in the group in one go. You can't do this with reload()
because it will re-import each module before its dependencies have been refreshed, allowing old references to creep into new modules.
如果您有循环依赖关系,这是非常常见的,例如当您处理重新加载一个包时,您必须一次性卸载组中的所有模块。您不能使用reload()来执行这个操作,因为它将在更新依赖项之前重新导入每个模块,从而允许旧的引用进入新的模块。
The only way to do it in this case is to hack sys.modules
, which is kind of unsupported. You'd have to go through and delete each sys.modules
entry you wanted to be reloaded on next import, and also delete entries whose values are None
to deal with an implementation issue to do with caching failed relative imports. It's not terribly nice but as long as you have a fully self-contained set of dependencies that doesn't leave references outside its codebase, it's workable.
在这种情况下,唯一的方法就是攻击sys。模块,这是不支持的。你必须通过并删除每个系统。您希望在下一次导入时重新加载模块条目,并删除其值为None的条目,以处理与缓存失败的相对导入有关的实现问题。这不是很好,但是只要你有一个完全自包含的依赖集,它不会在代码库之外留下引用,它是可行的。
It's probably best to restart the server. :-)
最好重新启动服务器。:-)
#5
48
if 'myModule' in sys.modules:
del sys.modules["myModule"]
#6
28
For Python 2 use built-in function reload():
对于Python 2,使用内置函数reload():
reload(module)
For Python 2 and 3.2–3.3 use reload from module imp:
对于Python 2和3.2-3.3使用模块imp的重新加载:
import imp
imp.reload(module)
But imp
is deprecated since version 3.4 in favor of importlib, so use:
但是,由于版本3.4支持importlib, imp已被弃用,所以使用:
import importlib
importlib.reload(module)
or
或
from importlib import reload
reload(module)
#7
19
The following code allows you Python 2/3 compatibility:
下面的代码允许Python 2/3兼容性:
try:
reload
except NameError:
# Python 3
from imp import reload
The you can use it as reload()
in both versions which makes things simpler.
您可以在两个版本中使用它作为reload(),这使得事情变得更简单。
#8
12
The accepted answer doesn't handle the from X import Y case. This code handles it and the standard import case as well:
被接受的答案不能处理X导入Y的情况。此代码处理它和标准导入案例:
def importOrReload(module_name, *names):
import sys
if module_name in sys.modules:
reload(sys.modules[module_name])
else:
__import__(module_name, fromlist=names)
for name in names:
globals()[name] = getattr(sys.modules[module_name], name)
# use instead of: from dfly_parser import parseMessages
importOrReload("dfly_parser", "parseMessages")
In the reloading case, we reassign the top level names to the values stored in the newly reloaded module, which updates them.
在重新加载的情况下,我们将顶层的名称重新分配给存储在新重载模块中的值,这些值将更新它们。
#9
5
For those like me who want to unload all modules (when running in the Python interpreter under Emacs):
对于那些想要卸载所有模块的人(在Emacs中运行Python解释器时):
for mod in sys.modules.values():
reload(mod)
More information is in Reloading Python modules.
更多信息在重新加载Python模块中。
#10
4
Enthought Traits has a module that works fairly well for this. https://traits.readthedocs.org/en/4.3.0/_modules/traits/util/refresh.html
Enthought Traits有一个很好的模块。https://traits.readthedocs.org/en/4.3.0/_modules/traits/util/refresh.html
It will reload any module that has been changed, and update other modules and instanced objects that are using it. It does not work most of the time with __very_private__
methods, and can choke on class inheritance, but it saves me crazy amounts of time from having to restart the host application when writing PyQt guis, or stuff that runs inside programs such as Maya or Nuke. It doesn't work maybe 20-30 % of the time, but it's still incredibly helpful.
它将重新加载已更改的任何模块,并更新正在使用它的其他模块和实例对象。它在大多数情况下都不使用__very_private__方法,并且可以在类继承上阻塞,但是它节省了大量的时间,因为在编写PyQt gui时,必须重新启动主机应用程序,或者在诸如Maya或Nuke之类的程序中运行。它可能在20- 30%的时间内不起作用,但它仍然非常有用。
Enthought's package doesn't reload files the moment they change - you have to call it explicitely - but that shouldn't be all that hard to implement if you really need it
Enthought的包在它们改变的时候不会重新加载文件——你必须明确地调用它——但是如果你真的需要它,它就不那么难实现了。
#11
2
This is the modern way of reloading a module:
这是重新加载模块的现代方法:
from importlib import reload as modulereload
Just type modulereload(MODULE_NAME)
, replacing MODULE_NAME
with the name of the module you want to reload.
只需键入modulereload(MODULE_NAME),用要重新加载的模块的名称替换MODULE_NAME。
For example, modulereload(math)
will reload the math function.
例如,modulereload(math)将重新加载math函数。
#12
1
for me for case of Abaqus it is the way it works. Imagine your file is Class_VerticesEdges.py
对我来说,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'])
#13
1
If you are not in a server, but developing and need to frequently reload a module, here's a nice tip.
如果您不是在服务器中,但是开发和需要频繁地重新加载一个模块,这里有一个很好的提示。
First, make sure you are using the excellent IPython shell, from the Jupyter Notebook project. After installing Jupyter, you can start it with jupyter console
, or even better jupyter qtconsole
to have a nice colorized console with code completion in any OS.
首先,确保您使用的是优秀的IPython shell,来自于Jupyter笔记本项目。在安装了Jupyter之后,您可以使用Jupyter控制台或更好的Jupyter qtconsole启动它,它有一个漂亮的彩色控制台,在任何操作系统中都有代码完成。
Now in your shell, type:
在你的壳里,输入:
%reload_ext autoreload
%autoreload 2
Now, every time you run your script, your modules will be reloaded.
现在,每次运行脚本时,模块都会被重新加载。
Beyond the 2
, there are other options of the autoreload magic:
除了这2个,还有其他的autoreload魔术的选择:
%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.
#14
0
I got a lot of trouble trying to reload something inside Sublime Text, but finally I could wrote this utility to reload modules on Sublime Text based on the code sublime_plugin.py
uses to reload modules.
我有很多麻烦试图在崇高的文本中重新加载一些东西,但是最后我可以编写这个实用程序来重新加载基于代码sublime_plugin的基于崇高文本的模块。py用于重载模块。
This below accepts you to reload modules from paths with spaces on their names, then later after reloading you can just import as you usually do.
下面的内容将允许您从带有空格的路径上重新加载模块,然后在重新加载之后,您可以像往常一样导入。
def reload_module(full_module_name):
"""
Assuming the folder `full_module_name` is a folder inside some
folder on the python sys.path, for example, sys.path as `C:/`, and
you are inside the folder `C:/Path With Spaces` on the file
`C:/Path With Spaces/main.py` and want to re-import some files on
the folder `C:/Path With Spaces/tests`
@param full_module_name the relative full path to the module file
you want to reload from a folder on the
python `sys.path`
"""
import imp
import sys
import importlib
if full_module_name in sys.modules:
module_object = sys.modules[full_module_name]
module_object = imp.reload( module_object )
else:
importlib.import_module( full_module_name )
def run_tests():
print( "\n\n" )
reload_module( "Path With Spaces.tests.semantic_linefeed_unit_tests" )
reload_module( "Path With Spaces.tests.semantic_linefeed_manual_tests" )
from .tests import semantic_linefeed_unit_tests
from .tests import semantic_linefeed_manual_tests
semantic_linefeed_unit_tests.run_unit_tests()
semantic_linefeed_manual_tests.run_manual_tests()
if __name__ == "__main__":
run_tests()
If you run for the first time, this should load the module, but if later you can again the method/function run_tests()
it will reload the tests files. With Sublime Text (Python 3.3.6
) this happens a lot because its interpreter never closes (unless you restart Sublime Text, i.e., the Python3.3
interpreter).
如果您第一次运行,这将加载模块,但是如果稍后您可以再次使用方法/函数run_tests(),它将重新加载测试文件。有了卓越的文本(Python 3.3.6),这经常发生,因为它的解释器永远不会关闭(除非您重新启动了崇高的文本,即:Python3.3解释器)。
#15
0
2018-02-01
2018-02-01
- module
foo
must be imported successfully in advance. - 模块foo必须预先成功导入。
-
from importlib import reload
,reload(foo)
- 从importlib导入reload, reload(foo)
31.5. importlib — The implementation of import — Python 3.6.4 documentation
31.5。importlib -导入- Python 3.6.4文档的实现。
#16
-1
Another way could be to import the module in a function. This way when the function completes the module gets garbage collected.
另一种方法是在函数中导入模块。这样当函数完成时,模块就会被垃圾回收。
#1
527
You can reload a module when it has already been imported by using the reload
builtin function in Python 2:
当使用Python 2中的reload builtin函数导入时,您可以重新加载模块。
import foo
while True:
# Do some things.
if is_changed(foo):
foo = reload(foo)
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.
在Python 3中,reload被移动到imp模块。在3.4中,imp被弃用,支持importlib,并将reload添加到后者。当目标3或更高时,在调用reload或导入时引用适当的模块。
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.
我认为这就是你想要的。像Django的开发服务器这样的Web服务器使用它,这样您就可以看到代码更改的效果,而无需重新启动服务器进程本身。
To quote from the docs:
引用文件:
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.
Python模块的代码被重新编译,模块级代码被重新执行,定义了一组新的对象,这些对象绑定到模块字典中的名称。扩展模块的init功能不是第二次调用。与Python中的所有其他对象一样,旧对象只有在引用计数降为零之后才被回收。模块名称空间中的名称更新为指向任何新的或已更改的对象。其他对旧对象的引用(比如模块外部的名称)不会被反弹来引用新对象,并且必须在每个名称空间中进行更新,如果需要的话。
As you noted in your question, you'll have to reconstruct Foo
objects if the Foo
class resides in the foo
module.
正如您在问题中提到的,如果Foo类驻留在Foo模块中,就必须重新构造Foo对象。
#2
217
In Python 3.0–3.3 you would use: imp.reload(module)
在Python 3.0-3.3中,您将使用:impl .reload(模块)
The BDFL has answered this question.
BDFL回答了这个问题。
However, imp
was deprecated in 3.4, in favour of importlib
(thanks @Stefan!).
然而,imp在3.4中被弃用,转而支持importlib(感谢@Stefan!)
I think, therefore, you’d now use importlib.reload(module)
, although I’m not sure.
因此,我认为您现在使用importlib.reload(模块),尽管我不确定。
#3
72
It can be especially difficult to delete a module if it is not pure Python.
如果一个模块不是纯Python,那么删除它就特别困难。
Here is some information from: How do I really delete an imported module?
这里有一些信息:如何真正删除导入的模块?
You can use sys.getrefcount() to find out the actual number of references.
您可以使用sys.getrefcount()来查找实际引用的数量。
>>> import sys, empty, os
>>> sys.getrefcount(sys)
9
>>> sys.getrefcount(os)
6
>>> sys.getrefcount(empty)
3
Numbers greater than 3 indicate that it will be hard to get rid of the module. The homegrown "empty" (containing nothing) module should be garbage collected after
大于3的数字表明很难去掉模块。本地的“空”(不包含任何)模块应该被垃圾回收。
>>> del sys.modules["empty"]
>>> del empty
as the third reference is an artifact of the getrefcount() function.
因为第三个引用是getrefcount()函数的一个工件。
#4
54
reload(module)
, but only if it's completely stand-alone. If anything else has a reference to the module (or any object belonging to the module), then you'll get subtle and curious errors caused by the old code hanging around longer than you expected, and things like isinstance
not working across different versions of the same code.
reload(模块),但必须完全独立。如果对模块(或模块的任何对象)有任何引用,那么您将会得到一些由旧代码所导致的微妙的、奇怪的错误,这些错误会比您预期的时间长一些,比如isinstance没有在相同代码的不同版本中工作。
If you have one-way dependencies, you must also reload all modules that depend on the the reloaded module to get rid of all the references to the old code. And then reload modules that depend on the reloaded modules, recursively.
如果有单向依赖关系,则还必须重新加载依赖于重新加载模块的所有模块,以消除对旧代码的所有引用。然后重新加载依赖于重新加载模块的模块,递归地进行。
If you have circular dependencies, which is very common for example when you are dealing with reloading a package, you must unload all the modules in the group in one go. You can't do this with reload()
because it will re-import each module before its dependencies have been refreshed, allowing old references to creep into new modules.
如果您有循环依赖关系,这是非常常见的,例如当您处理重新加载一个包时,您必须一次性卸载组中的所有模块。您不能使用reload()来执行这个操作,因为它将在更新依赖项之前重新导入每个模块,从而允许旧的引用进入新的模块。
The only way to do it in this case is to hack sys.modules
, which is kind of unsupported. You'd have to go through and delete each sys.modules
entry you wanted to be reloaded on next import, and also delete entries whose values are None
to deal with an implementation issue to do with caching failed relative imports. It's not terribly nice but as long as you have a fully self-contained set of dependencies that doesn't leave references outside its codebase, it's workable.
在这种情况下,唯一的方法就是攻击sys。模块,这是不支持的。你必须通过并删除每个系统。您希望在下一次导入时重新加载模块条目,并删除其值为None的条目,以处理与缓存失败的相对导入有关的实现问题。这不是很好,但是只要你有一个完全自包含的依赖集,它不会在代码库之外留下引用,它是可行的。
It's probably best to restart the server. :-)
最好重新启动服务器。:-)
#5
48
if 'myModule' in sys.modules:
del sys.modules["myModule"]
#6
28
For Python 2 use built-in function reload():
对于Python 2,使用内置函数reload():
reload(module)
For Python 2 and 3.2–3.3 use reload from module imp:
对于Python 2和3.2-3.3使用模块imp的重新加载:
import imp
imp.reload(module)
But imp
is deprecated since version 3.4 in favor of importlib, so use:
但是,由于版本3.4支持importlib, imp已被弃用,所以使用:
import importlib
importlib.reload(module)
or
或
from importlib import reload
reload(module)
#7
19
The following code allows you Python 2/3 compatibility:
下面的代码允许Python 2/3兼容性:
try:
reload
except NameError:
# Python 3
from imp import reload
The you can use it as reload()
in both versions which makes things simpler.
您可以在两个版本中使用它作为reload(),这使得事情变得更简单。
#8
12
The accepted answer doesn't handle the from X import Y case. This code handles it and the standard import case as well:
被接受的答案不能处理X导入Y的情况。此代码处理它和标准导入案例:
def importOrReload(module_name, *names):
import sys
if module_name in sys.modules:
reload(sys.modules[module_name])
else:
__import__(module_name, fromlist=names)
for name in names:
globals()[name] = getattr(sys.modules[module_name], name)
# use instead of: from dfly_parser import parseMessages
importOrReload("dfly_parser", "parseMessages")
In the reloading case, we reassign the top level names to the values stored in the newly reloaded module, which updates them.
在重新加载的情况下,我们将顶层的名称重新分配给存储在新重载模块中的值,这些值将更新它们。
#9
5
For those like me who want to unload all modules (when running in the Python interpreter under Emacs):
对于那些想要卸载所有模块的人(在Emacs中运行Python解释器时):
for mod in sys.modules.values():
reload(mod)
More information is in Reloading Python modules.
更多信息在重新加载Python模块中。
#10
4
Enthought Traits has a module that works fairly well for this. https://traits.readthedocs.org/en/4.3.0/_modules/traits/util/refresh.html
Enthought Traits有一个很好的模块。https://traits.readthedocs.org/en/4.3.0/_modules/traits/util/refresh.html
It will reload any module that has been changed, and update other modules and instanced objects that are using it. It does not work most of the time with __very_private__
methods, and can choke on class inheritance, but it saves me crazy amounts of time from having to restart the host application when writing PyQt guis, or stuff that runs inside programs such as Maya or Nuke. It doesn't work maybe 20-30 % of the time, but it's still incredibly helpful.
它将重新加载已更改的任何模块,并更新正在使用它的其他模块和实例对象。它在大多数情况下都不使用__very_private__方法,并且可以在类继承上阻塞,但是它节省了大量的时间,因为在编写PyQt gui时,必须重新启动主机应用程序,或者在诸如Maya或Nuke之类的程序中运行。它可能在20- 30%的时间内不起作用,但它仍然非常有用。
Enthought's package doesn't reload files the moment they change - you have to call it explicitely - but that shouldn't be all that hard to implement if you really need it
Enthought的包在它们改变的时候不会重新加载文件——你必须明确地调用它——但是如果你真的需要它,它就不那么难实现了。
#11
2
This is the modern way of reloading a module:
这是重新加载模块的现代方法:
from importlib import reload as modulereload
Just type modulereload(MODULE_NAME)
, replacing MODULE_NAME
with the name of the module you want to reload.
只需键入modulereload(MODULE_NAME),用要重新加载的模块的名称替换MODULE_NAME。
For example, modulereload(math)
will reload the math function.
例如,modulereload(math)将重新加载math函数。
#12
1
for me for case of Abaqus it is the way it works. Imagine your file is Class_VerticesEdges.py
对我来说,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'])
#13
1
If you are not in a server, but developing and need to frequently reload a module, here's a nice tip.
如果您不是在服务器中,但是开发和需要频繁地重新加载一个模块,这里有一个很好的提示。
First, make sure you are using the excellent IPython shell, from the Jupyter Notebook project. After installing Jupyter, you can start it with jupyter console
, or even better jupyter qtconsole
to have a nice colorized console with code completion in any OS.
首先,确保您使用的是优秀的IPython shell,来自于Jupyter笔记本项目。在安装了Jupyter之后,您可以使用Jupyter控制台或更好的Jupyter qtconsole启动它,它有一个漂亮的彩色控制台,在任何操作系统中都有代码完成。
Now in your shell, type:
在你的壳里,输入:
%reload_ext autoreload
%autoreload 2
Now, every time you run your script, your modules will be reloaded.
现在,每次运行脚本时,模块都会被重新加载。
Beyond the 2
, there are other options of the autoreload magic:
除了这2个,还有其他的autoreload魔术的选择:
%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.
#14
0
I got a lot of trouble trying to reload something inside Sublime Text, but finally I could wrote this utility to reload modules on Sublime Text based on the code sublime_plugin.py
uses to reload modules.
我有很多麻烦试图在崇高的文本中重新加载一些东西,但是最后我可以编写这个实用程序来重新加载基于代码sublime_plugin的基于崇高文本的模块。py用于重载模块。
This below accepts you to reload modules from paths with spaces on their names, then later after reloading you can just import as you usually do.
下面的内容将允许您从带有空格的路径上重新加载模块,然后在重新加载之后,您可以像往常一样导入。
def reload_module(full_module_name):
"""
Assuming the folder `full_module_name` is a folder inside some
folder on the python sys.path, for example, sys.path as `C:/`, and
you are inside the folder `C:/Path With Spaces` on the file
`C:/Path With Spaces/main.py` and want to re-import some files on
the folder `C:/Path With Spaces/tests`
@param full_module_name the relative full path to the module file
you want to reload from a folder on the
python `sys.path`
"""
import imp
import sys
import importlib
if full_module_name in sys.modules:
module_object = sys.modules[full_module_name]
module_object = imp.reload( module_object )
else:
importlib.import_module( full_module_name )
def run_tests():
print( "\n\n" )
reload_module( "Path With Spaces.tests.semantic_linefeed_unit_tests" )
reload_module( "Path With Spaces.tests.semantic_linefeed_manual_tests" )
from .tests import semantic_linefeed_unit_tests
from .tests import semantic_linefeed_manual_tests
semantic_linefeed_unit_tests.run_unit_tests()
semantic_linefeed_manual_tests.run_manual_tests()
if __name__ == "__main__":
run_tests()
If you run for the first time, this should load the module, but if later you can again the method/function run_tests()
it will reload the tests files. With Sublime Text (Python 3.3.6
) this happens a lot because its interpreter never closes (unless you restart Sublime Text, i.e., the Python3.3
interpreter).
如果您第一次运行,这将加载模块,但是如果稍后您可以再次使用方法/函数run_tests(),它将重新加载测试文件。有了卓越的文本(Python 3.3.6),这经常发生,因为它的解释器永远不会关闭(除非您重新启动了崇高的文本,即:Python3.3解释器)。
#15
0
2018-02-01
2018-02-01
- module
foo
must be imported successfully in advance. - 模块foo必须预先成功导入。
-
from importlib import reload
,reload(foo)
- 从importlib导入reload, reload(foo)
31.5. importlib — The implementation of import — Python 3.6.4 documentation
31.5。importlib -导入- Python 3.6.4文档的实现。
#16
-1
Another way could be to import the module in a function. This way when the function completes the module gets garbage collected.
另一种方法是在函数中导入模块。这样当函数完成时,模块就会被垃圾回收。