简体   繁体   English

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

[英]How do I unload (reload) a Python module?

I have a long-running Python server and would like to be able to upgrade a service without restarting the server.我有一个长期运行的 Python 服务器,并且希望能够在不重新启动服务器的情况下升级服务。 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()

You can reload a module when it has already been imported by using importlib.reload() :您可以使用importlib.reload()重新加载已经导入的模块:

from importlib import reload  # Python 3.4+
import foo

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

In Python 2,reload was a builtin.在 Python 2 中,reload是内置的。 In Python 3, it was moved to the imp module.在 Python 3 中,它被移至imp模块。 In 3.4, imp was deprecated in favor of importlib .在 3.4 中, imp弃用,取而代之的是importlib When targeting 3 or later, either reference the appropriate module when calling reload or import it.以 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 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.重新编译 Python 模块的代码并重新执行模块级代码,通过重用最初加载模块的加载器,定义一组新的对象,这些对象绑定到模块字典中的名称。 The init function of extension modules is not called a second time.扩展模块的init函数不会被第二次调用。
  • As with all other objects in Python the old objects are only reclaimed after their reference counts drop to zero.与 Python 中的所有其他对象一样,旧对象仅在其引用计数降至零后才会被回收。
  • 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.对旧对象的其他引用(例如模块外部的名称)不会重新引用以引用新对象,并且如果需要,必须在它们出现的每个命名空间中进行更新。

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

In Python 3.0–3.3 you would use: imp.reload(module)在 Python 3.0–3.3 中,您将使用: imp.reload(module)

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(module) ,尽管我不确定。

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.大于 3 的数字表示很难摆脱该模块。 The homegrown "empty" (containing nothing) module should be garbage collected after自制的“空”(不包含任何内容)模块应该在之后被垃圾收集

>>> del sys.modules["empty"]
>>> del empty

as the third reference is an artifact of the getrefcount() function.因为第三个引用是 getrefcount() 函数的工件。

reload(module) , but only if it's completely stand-alone. reload(module) ,但前提是它完全独立。 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.如果其他任何东西都引用了该模块(或属于该模块的任何对象),那么您将得到由旧代码比您预期的更长的时间引起的微妙而奇怪的错误,并且诸如isinstance之类的东西无法在不同版本的相同的代码。

If you have one-way dependencies, you must also reload all modules that depend on 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.在这种情况下,唯一的方法是破解sys.modules ,这是不受支持的。 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.您必须检查并删除您希望在下次导入时重新加载的每个sys.modules条目,并删除值为None的条目以处理与缓存失败的相对导入有关的实现问题。 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.这不是非常好,但只要你有一组完全独立的依赖项,不会在其代码库之外留下引用,它是可行的。

It's probably best to restart the server.最好重新启动服务器。 :-) :-)

For Python 2 use built-in function reload :对于 Python 2 ,使用内置函数reload

reload(module)

For Python 2 and Python 3.23.3 use reload from module imp :对于 Python 2Python 3.23.3使用从模块 imp reload

import imp
imp.reload(module)

For Python ≥ 3.4 , imp is deprecated in favor of importlib , so use this:对于 Python ≥ 3.4不推荐使用imp取而代之的是importlib ,所以使用这个:

import importlib
importlib.reload(module)

or:或者:

from importlib import reload
reload(module)

TL;DR: TL;博士:

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

if 'myModule' in sys.modules:  
    del sys.modules["myModule"]

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() ,这使事情变得更简单。

The accepted answer doesn't handle the from X import Y case.接受的答案不处理 from X import Y 的情况。 This code handles it and the standard import case as well:此代码处理它以及标准导入案例:

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.在重新加载的情况下,我们将顶级名称重新分配给存储在新重新加载的模块中的值,从而更新它们。

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.首先,确保您使用的是 Jupyter Notebook 项目中出色的IPython shell After installing Jupyter, you can start it with ipython , or jupyter console , or even better, jupyter qtconsole , which will give you a nice colorized console with code completion in any OS.安装 Jupyter 后,您可以使用ipythonjupyter console启动它,甚至更好的是jupyter qtconsole ,这将为您提供一个漂亮的彩色控制台,并在任何操作系统中完成代码完成。

Now in your shell, type:现在在你的 shell 中,输入:

%load_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.

Sure, it will also work on a Jupyter Notebook.当然,它也适用于 Jupyter Notebook。

This is the modern way of reloading a module:这是重新加载模块的现代方式:

from importlib import reload

If you want to support versions of Python older than 3.5, use this:如果要支持 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+

This defines a reload method which can be called with a module to reload it.这定义了一个reload方法,可以使用模块调用它来重新加载它。 For example, reload(math) will reload the math module.例如, reload(math)将重新加载math模块。

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 模块中。

Edit (Answer V2)编辑(答案 V2)

The solution from before is good for just getting the reset information, but it will not change all the references (more than reload but less then required).以前的解决方案仅用于获取重置信息,但它不会更改所有引用(超过reload但少于所需的)。 To actually set all the references as well, I had to go into the garbage collector, and rewrite the references there.要实际设置所有引用,我必须进入垃圾收集器,并在那里重写引用。 Now it works like a charm!现在它就像一个魅力!

Note that this will not work if the GC is turned off, or if reloading data that's not monitored by the GC.请注意,如果 GC 关闭,或者重新加载不受 GC 监控的数据,这不起作用。 If you don't want to mess with the GC, the original answer might be enough for you.如果您不想弄乱 GC,那么原始答案对您来说可能就足够了。

New code:新代码:

import importlib
import inspect
import gc
from enum import EnumMeta
from weakref import ref


_readonly_attrs = {'__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__',
               '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__func__', '__ge__', '__get__',
               '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__',
               '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__',
               '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__',
               '__subclasshook__', '__weakref__', '__members__', '__mro__', '__itemsize__', '__isabstractmethod__',
               '__basicsize__', '__base__'}


def reset_module(module, inner_modules_also=True):
    """
    This function is a stronger form of importlib's `reload` function. What it does, is that aside from reloading a
    module, it goes to the old instance of the module, and sets all the (not read-only) attributes, functions and classes
    to be the reloaded-module's
    :param module: The module to reload (module reference, not the name)
    :param inner_modules_also: Whether to treat ths module as a package as well, and reload all the modules within it.
    """

    # For the case when the module is actually a package
    if inner_modules_also:
        submods = {submod for _, submod in inspect.getmembers(module)
                   if (type(submod).__name__ == 'module') and (submod.__package__.startswith(module.__name__))}
        for submod in submods:
            reset_module(submod, True)

    # First, log all the references before reloading (because some references may be changed by the reload operation).
    module_tree = _get_tree_references_to_reset_recursively(module, module.__name__)

    new_module = importlib.reload(module)
    _reset_item_recursively(module, module_tree, new_module)


def _update_referrers(item, new_item):
    refs = gc.get_referrers(item)

    weak_ref_item = ref(item)
    for coll in refs:
        if type(coll) == dict:
            enumerator = coll.keys()
        elif type(coll) == list:
            enumerator = range(len(coll))
        else:
            continue

        for key in enumerator:

            if weak_ref_item() is None:
                # No refs are left in the GC
                return

            if coll[key] is weak_ref_item():
                coll[key] = new_item

def _get_tree_references_to_reset_recursively(item, module_name, grayed_out_item_ids = None):
    if grayed_out_item_ids is None:
        grayed_out_item_ids = set()

    item_tree = dict()
    attr_names = set(dir(item)) - _readonly_attrs
    for sub_item_name in attr_names:

        sub_item = getattr(item, sub_item_name)
        item_tree[sub_item_name] = [sub_item, None]

        try:
            # Will work for classes and functions defined in that module.
            mod_name = sub_item.__module__
        except AttributeError:
            mod_name = None

        # If this item was defined within this module, deep-reset
        if (mod_name is None) or (mod_name != module_name) or (id(sub_item) in grayed_out_item_ids) \
                or isinstance(sub_item, EnumMeta):
            continue

        grayed_out_item_ids.add(id(sub_item))
        item_tree[sub_item_name][1] = \
            _get_tree_references_to_reset_recursively(sub_item, module_name, grayed_out_item_ids)

    return item_tree


def _reset_item_recursively(item, item_subtree, new_item):

    # Set children first so we don't lose the current references.
    if item_subtree is not None:
        for sub_item_name, (sub_item, sub_item_tree) in item_subtree.items():

            try:
                new_sub_item = getattr(new_item, sub_item_name)
            except AttributeError:
                # The item doesn't exist in the reloaded module. Ignore.
                continue

            try:
                # Set the item
                _reset_item_recursively(sub_item, sub_item_tree, new_sub_item)
            except Exception as ex:
                pass

    _update_referrers(item, new_item)

Original Answer原始答案

As written in @bobince's answer, if there's already a reference to that module in another module (especially if it was imported with the as keyword like import numpy as np ), that instance will not be overwritten.正如@bobince 的回答所写,如果在另一个模块中已经有对该模块的引用(特别是如果它是使用as关键字导入的,例如import numpy as np ),则该实例不会被覆盖。

This proved quite problematic to me when applying tests that required a "clean-slate" state of the configuration modules, so I've written a function named reset_module that uses importlib 's reload function and recursively overwrites all the declared module's attributes.在应用需要配置模块的“干净”状态的测试时,这对我来说是一个很大的问题,因此我编写了一个名为reset_module的函数,它使用importlibreload函数并递归地覆盖所有声明的模块属性。 It has been tested with Python version 3.6.它已经用 Python 3.6 版进行了测试。

import importlib
import inspect
from enum import EnumMeta

_readonly_attrs = {'__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__',
               '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__func__', '__ge__', '__get__',
               '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__',
               '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__',
               '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__',
               '__subclasshook__', '__weakref__', '__members__', '__mro__', '__itemsize__', '__isabstractmethod__',
               '__basicsize__', '__base__'}


def reset_module(module, inner_modules_also=True):
    """
    This function is a stronger form of importlib's `reload` function. What it does, is that aside from reloading a
    module, it goes to the old instance of the module, and sets all the (not read-only) attributes, functions and classes
    to be the reloaded-module's
    :param module: The module to reload (module reference, not the name)
    :param inner_modules_also: Whether to treat ths module as a package as well, and reload all the modules within it.
    """

    new_module = importlib.reload(module)

    reset_items = set()

    # For the case when the module is actually a package
    if inner_modules_also:
        submods = {submod for _, submod in inspect.getmembers(module)
                   if (type(submod).__name__ == 'module') and (submod.__package__.startswith(module.__name__))}
        for submod in submods:
            reset_module(submod, True)

    _reset_item_recursively(module, new_module, module.__name__, reset_items)


def _reset_item_recursively(item, new_item, module_name, reset_items=None):
    if reset_items is None:
        reset_items = set()

    attr_names = set(dir(item)) - _readonly_attrs

    for sitem_name in attr_names:

        sitem = getattr(item, sitem_name)
        new_sitem = getattr(new_item, sitem_name)

        try:
            # Set the item
            setattr(item, sitem_name, new_sitem)

            try:
                # Will work for classes and functions defined in that module.
                mod_name = sitem.__module__
            except AttributeError:
                mod_name = None

            # If this item was defined within this module, deep-reset
            if (mod_name is None) or (mod_name != module_name) or (id(sitem) in reset_items) \
                    or isinstance(sitem, EnumMeta):  # Deal with enums
                continue

            reset_items.add(id(sitem))
            _reset_item_recursively(sitem, new_sitem, module_name, reset_items)
        except Exception as ex:
            raise Exception(sitem_name) from ex

Note: Use with care!注意:小心使用! Using these on non-peripheral modules (modules that define externally-used classes, for example) might lead to internal problems in Python (such as pickling/un-pickling issues).在非外围模块(例如,定义外部使用的类的模块)上使用这些可能会导致 Python 中的内部问题(例如酸洗/非酸洗问题)。

Enthought Traits has a module that works fairly well for this. Enthought Traits 有一个模块可以很好地解决这个问题。 https://traits.readthedocs.org/en/4.3.0/_modules/traits/util/refresh.html 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.它在大多数情况下不适用于__very_private__方法,并且可能会阻塞类继承,但它为我节省了大量时间,无需在编写 PyQt guis 或在诸如 Maya 或 Nuke 等程序中运行的东西时重新启动主机应用程序. It doesn't work maybe 20-30 % of the time, but it's still incredibly helpful.它可能在 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 的包不会在文件更改的那一刻重新加载文件——你必须明确地调用它——但如果你真的需要它,这应该不难实现

Other option.其他选项。 See that Python default importlib.reload will just reimport the library passed as an argument.看到 Python 默认importlib.reload只会重新导入作为参数传递的库。 It won't reload the libraries that your lib import.不会重新加载您的 lib 导入的库。 If you changed a lot of files and have a somewhat complex package to import, you must do a deep reload .如果您更改了很多文件并且要导入一个有些复杂的包,则必须进行深度重新加载

If you have IPython or Jupyter installed, you can use a function to deep reload all libs:如果您安装了IPythonJupyter ,则可以使用函数来深度重新加载所有库:

from IPython.lib.deepreload import reload as dreload
dreload(foo)

If you don't have Jupyter, install it with this command in your shell:如果您没有 Jupyter,请在 shell 中使用以下命令安装它:

pip3 install jupyter

Those who are using python 3 and reload from importlib.那些使用 python 3 并从 importlib 重新加载的人。

If you have problems like it seems that module doesn't reload... That is because it needs some time to recompile pyc (up to 60 sec).I writing this hint just that you know if you have experienced this kind of problem.如果您遇到模块似乎没有重新加载的问题......那是因为它需要一些时间来重新编译 pyc(最多 60 秒)。我写这个提示只是为了让您知道您是否遇到过这种问题。

2018-02-01 2018-02-01

  1. module foo must be imported successfully in advance.模块foo必须提前成功导入。
  2. from importlib import reload , reload(foo) from importlib import reloadreload(foo)

31.5. 31.5。 importlib — The implementation of import — Python 3.6.4 documentation importlib — 导入的实现 — Python 3.6.4 文档

for me for case of Abaqus it is the way it works.对我来说,就 Abaqus 而言,这就是它的工作方式。 Imagine your file is Class_VerticesEdges.py想象一下你的文件是 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'])

If you encounter the following error, this answer may help you to get a solution:如果您遇到以下错误,此答案可能会帮助您获得解决方案:

 Traceback (most recent call last):回溯(最近一次通话最后): 
 File "FFFF", line 1, in文件“FFFF”,第 1 行,在  
NameError: name 'YYYY' is not defined NameError: 名称 'YYYY' 未定义

OR或者

Traceback (most recent call last):回溯(最近一次通话最后):
 File "FFFF", line 1, in文件“FFFF”,第 1 行,在 
 File "/usr/local/lib/python3.7/importlib/__init__.py", line 140, in reload文件“/usr/local/lib/python3.7/importlib/__init__.py”,第 140 行,重新加载
   raise TypeError("reload() argument must be a module") raise TypeError("reload() 参数必须是一个模块")
TypeError: reload() argument must be a module TypeError: reload() 参数必须是一个模块

In case you have an import like the one below, you may need to use the sys.modules to get the module you want to reload:如果您有如下所示的导入,您可能需要使用sys.modules来获取要重新加载的模块:

  import importlib
  import sys

  from YYYY.XXX.ZZZ import CCCC
  import AAA.BBB.CC


  def reload(full_name)
    if full_name in sys.modules:
      importlib.reload(sys.modules[full_name])


  reload('YYYY.XXX.ZZZ') # this is fine in both cases
  reload('AAA.BBB.CC')  

  importlib.reload(YYYY.XXX.ZZZ) # in my case: this fails
  importlib.reload(AAA.BBB.CC)   #             and this is ok

The main issue is that the importlib.reload accepts module only not string.主要问题是importlib.reload只接受模块而不接受字符串。

Removing modules from sys.modules requires 'None' types to be deleted as well.从 sys.modules 中删除模块也需要删除“无”类型。

Method 1:方法一:

import sys
import json  ##  your module

for mod in [ m for m in sys.modules if m.lstrip('_').startswith('json') or sys.modules[m] == None ]: del sys.modules[mod]

print( json.dumps( [1] ) )  ##  test if functionality has been removed

Method 2, using bookkeeping entries, to remove all dependencies:方法 2,使用簿记条目,删除所有依赖项:

import sys

before_import = [mod for mod in sys.modules]
import json  ##  your module
after_import = [mod for mod in sys.modules if mod not in before_import]

for mod in [m for m in sys.modules if m in after_import or sys.modules[m] == None]: del sys.modules[mod]

print( json.dumps( [2] ) )  ##  test if functionality has been removed

Optional, just to be certain all entries are out, if you so choose:可选,只是为了确定所有条目都已输出,如果您选择:

import gc
gc.collect()

Python will not re-calculate submodule address when reload , event if it is in sys.modules Python 在reload时不会重新计算子模块地址,如果它在sys.modules中,则事件

Here is a workaround, not perfect but worked.这是一种解决方法,虽然不完美但有效。

# 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

Another way could be to import the module in a function.另一种方法是在函数中导入模块。 This way when the function completes the module gets garbage collected.这样,当函数完成时,模块就会被垃圾收集。

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 Text 中的内容时遇到了很多麻烦,但最后我可以编写这个实用程序来根据sublime_plugin.py用于重新加载模块的代码在 Sublime Text 上重新加载模块。

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.如果您第一次运行,这应该加载模块,但如果以后您可以再次使用方法/函数run_tests()它将重新加载测试文件。 With Sublime Text ( Python 3.3.6 ) this happens a lot because its interpreter never closes (unless you restart Sublime Text, ie, the Python3.3 interpreter).对于 Sublime Text ( Python 3.3.6 ),这种情况经常发生,因为它的解释器永远不会关闭(除非你重新启动 Sublime Text,即Python3.3解释器)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM