如何重新加载所有导入的模块? [英] How to reload all imported modules?

查看:62
本文介绍了如何重新加载所有导入的模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个模块,我想重新加载而不必重新启动 Sublime Text,同时我正在开发一个 Sublime Text 包.

I have several modules, I would like to reload without having to restart Sublime Text, while I am developing a Sublime Text package.

我正在运行 Sublime Text build 3142,它带有 python3.3 连续运行其包/插件.但是,在开发插件时,我导入了添加到路径中的第三方模块:

I am running Sublime Text build 3142 which comes with python3.3 running continuously its packages/plugins. However while developing a plugin, I import a third part module I added to path as:

import os
import sys

def assert_path(module):
    """
        Import a module from a relative path
        https://stackoverflow.com/questions/279237/import-a-module-from-a-relative-path
    """
    if module not in sys.path:
        sys.path.insert( 0, module )

current_directory = os.path.dirname( os.path.realpath( __file__ ) )
assert_path( os.path.join( current_directory, 'six' ) ) # https://github.com/benjaminp/six

import six

但是当我编辑模块six的源代码时,我需要再次关闭并打开Sublime Text,否则Sublime Text不会得到six python的更改模块.

But when I edit the source code of the module six I need to close and open Sublime Text again, otherwise Sublime Text does not gets the changes to the six python module.

到目前为止我尝试过的一些代码:

Some code I have tried so far:

print( sys.modules )
import git_wrapper
imp.reload( find_forks )
imp.reload( git_wrapper )
imp.reload( sys )

  1. 从控制台
  2. 重新加载模块给出 NameError: name 'reload' is not定义

推荐答案

要列出所有导入的模块,可以使用 sys.modules.values().

To list all imported modules, you can use sys.modules.values().

import sys
sys.modules.values()

sys.modules 是一个字典,将模块的字符串名称映射到它们的引用.

sys.modules is a dictionary that maps the string names of modules to their references.

要重新加载模块,您可以遍历从上面返回的列表并对每个模块调用 importlib.reload:

To reload modules, you can loop over the returned list from above and call importlib.reload on each one:

import importlib
for module in sys.modules.values():
    importlib.reload(module)

这篇关于如何重新加载所有导入的模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆