Python importlib 模块,reload() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用importlib.reload()

项目:Sverchok    作者:Sverchok    | 项目源码 | 文件源码
def load_text(self, context=None):
        if self.text_file in bpy.data.texts:
            if self.text_file == 'Text':
                self.text_file = ''
                return
            text = text_remap(self.text_file)
            try:
                mod = importlib.import_module("svrx.nodes.script.{}".format(text))
                importlib.reload(mod)
            except Exception as err:
                error.show(self, err, script=True)
            else:
                self.adjust_sockets()
                self.color = READY_COLOR
                self.use_custom_color = True
        else:
            pass #  fail
项目:rosimport    作者:pyros-dev    | 项目源码 | 文件源码
def test_importlib_importmodule_relative_srv(self):

        assert __package__
        # Verify that files exists and are dynamically importable
        test_srvs = importlib.import_module('.srv', package=__package__)
        test_msgs = importlib.import_module('.msg', package=__package__)

        self.assert_test_service_classes(test_srvs.TestSrv, test_srvs.TestSrvRequest, test_srvs.TestSrvResponse,
                                         test_srvs.TestSrvDeps, test_srvs.TestSrvDepsRequest, test_srvs.TestSrvDepsResponse,
                                         test_msgs.TestRosMsgDeps, test_msgs.TestRosMsg)

        if hasattr(importlib, 'reload'):  # recent version of importlib
            # attempting to reload
            importlib.reload(test_srvs)
        else:
            pass

        assert test_srvs is not None
项目:rosimport    作者:pyros-dev    | 项目源码 | 文件源码
def test_importlib_importmodule_relative_msg(self):

        assert __package__
        # Verify that files exists and are dynamically importable
        subtest_msgs = importlib.import_module('.msg', package=__package__)
        test_msgs = importlib.import_module('test_rosimport.msg', package=__package__)

        self.assert_test_message_classes(subtest_msgs.SubTestMsg, subtest_msgs.SubTestMsgDeps, test_msgs.TestRosMsgDeps, test_msgs.TestRosMsg)

        if hasattr(importlib, 'reload'):  # recent version of importlib
            # attempting to reload
            importlib.reload(test_msgs)
        else:
            pass

        assert test_msgs is not None
项目:rosimport    作者:pyros-dev    | 项目源码 | 文件源码
def test_importlib_importmodule_relative_msg_from_absolute(self):

        assert __package__
        # Verify that files exists and are dynamically importable
        subtest_msgs = importlib.import_module('test_rosimport.subtests.msg')
        test_msgs = importlib.import_module('test_rosimport.msg')

        self.assert_test_message_classes(subtest_msgs.SubTestMsg, subtest_msgs.SubTestMsgDeps, test_msgs.TestRosMsgDeps, test_msgs.TestRosMsg)

        if hasattr(importlib, 'reload'):  # recent version of importlib
            # attempting to reload
            importlib.reload(test_msgs)
        else:
            pass

        assert test_msgs is not None
项目:rosimport    作者:pyros-dev    | 项目源码 | 文件源码
def test_importlib_importmodule_relative_srv(self):

        assert __package__
        # Verify that files exists and are dynamically importable
        subtest_srvs = importlib.import_module('.srv', package=__package__)
        test_msgs = importlib.import_module('test_rosimport.msg', package=__package__)

        self.assert_test_service_classes(subtest_srvs.SubTestSrv, subtest_srvs.SubTestSrvRequest, subtest_srvs.SubTestSrvResponse,
                                         subtest_srvs.SubTestSrvDeps, subtest_srvs.SubTestSrvDepsRequest, subtest_srvs.SubTestSrvDepsResponse,
                                         test_msgs.TestRosMsgDeps, test_msgs.TestRosMsg)

        if hasattr(importlib, 'reload'):  # recent version of importlib
            # attempting to reload
            importlib.reload(subtest_srvs)
        else:
            pass

        assert subtest_srvs is not None
项目:hangoutsbot    作者:das7pad    | 项目源码 | 文件源码
def load_module(module_path):
    """(re) load an external module

    Args:
        module_path: string, the path to the module relative to the main script

    Returns:
        boolean, True if no Exception was raised on (re)load, otherwise False
    """
    message = "search for plugin in sys.modules"
    try:
        if module_path in sys.modules:
            message = "reload"
            importlib.reload(sys.modules[module_path])

        else:
            message = "import"
            importlib.import_module(module_path)

        return True
    except:             # capture all Exceptions   # pylint: disable=bare-except
        logger.exception("load_module %s: %s", module_path, message)
        return False
项目:hangoutsbot    作者:das7pad    | 项目源码 | 文件源码
def reload_plugin(bot, module_path):
    """reload a plugin and keep track of multiple reloads

    Note: the plugin may reset the sentinal on a successfull internal load

    Args:
        module_path: string, plugin path on disk relative to the main script

    Returns:
        boolean, False if the plugin may not be reloaded again, otherwise True
    """
    repeat = SENTINALS.setdefault(module_path, 0)
    if repeat >= 3:
        logger.critical('too many reloads of %s, enter failstate', module_path)
        return False
    SENTINALS[module_path] += 1
    await unload(bot, module_path)
    await load(bot, module_path)
    return True
项目:endrebot0    作者:endreman0    | 项目源码 | 文件源码
def reload(ctx, *modules):
    for mod in modules:
        if mod == 'config':
            with open('config.json', encoding='utf-8') as f:
                ctx.bot.config = json.load(f)
        else:
            module_name = 'endrebot0.commands.{}'.format(mod)
            module = sys.modules.get(module_name)
            if module is not None:
                if hasattr(module, 'listeners'):
                    del module.listeners
                if hasattr(module, 'commands'):
                    del module.commands
            importlib.reload(module)
            ctx.bot.add_module(module)
            if hasattr(module, 'listeners'):
                for listener in module.listeners.get('on_ready', ()):
                    await listener(ctx.bot)
    return 'Reloaded %d module(s)' % len(modules)
项目:loopchain    作者:theloopkr    | 项目源码 | 文件源码
def load_configure_json(self, configure_file_path: str) -> None:
        """method for reading and applying json configuration.
        :param configure_file_path: json configure file path
        :return: None
        """
        print(f"try load configure from json file ({configure_file_path})")

        try:
            with open(f"{configure_file_path}") as json_file:
                json_data = json.load(json_file)

            for configure_key, configure_value in json_data.items():
                try:
                    configure_type, configure_value = self.__check_value_type(configure_key, configure_value)

                    self.__set_configure(configure_key, configure_type, configure_value)
                except Exception as e:
                    # no configure value
                    print(f"this is not configure key({configure_key}): {e}")

        except Exception as e:
            exit(f"cannot open json file in ({configure_file_path}): {e}")

        importlib.reload(loopchain.utils)
项目:pcbot    作者:pckv    | 项目源码 | 文件源码
def reload(name: str):
    """ Reload a plugin.

    This must be called from an on_reload function or coroutine.
    """
    if name in plugins:
        # Remove all registered commands
        if hasattr(plugins[name], "__commands"):
            delattr(plugins[name], "__commands")

        # Remove all registered events from the given plugin
        for event_name, funcs in events.items():
            for func in funcs:
                if func.__module__.endswith(name):
                    events[event_name].remove(func)

        plugins[name] = importlib.reload(plugins[name])

        logging.debug("Reloaded plugin {}".format(name))
项目:exit_code_dev    作者:TheCyaniteProject    | 项目源码 | 文件源码
def page_payme(self):
        global sitelocker_ver
        global riddleme_mode
        global hackable
        hackable = False
        sitelocker_ver = False
        riddleme_mode = False
        tkinter_ui.set_url('https://www.payme.net')
        import data.sites.payme.payme_site as payme_site
        importlib.reload(payme_site)
        payme_site.web_site(tkinter_ui.web_page, tkinter_ui.go_from)
        return
        '''
        hackable = [email_site.email_user, email_site.hack_in]
        if not email_site.sitelocker == None:
            sitelocker_ver = email_site.sitelocker
        if not email_site.riddleme == None:
            if not email_site.riddleme.lower() == 'false':
                riddleme_mode = True'''
项目:exit_code_dev    作者:TheCyaniteProject    | 项目源码 | 文件源码
def page_easybits(self):
        global sitelocker_ver
        global riddleme_mode
        global hackable
        hackable = False
        sitelocker_ver = False
        riddleme_mode = False
        tkinter_ui.set_url('https://www.easybits.com')
        import data.sites.easybits.easybits_site as easybits_site
        importlib.reload(easybits_site)
        easybits_site.web_site(tkinter_ui.web_page, tkinter_ui.go_from)
        return
        '''
        hackable = [email_site.email_user, email_site.hack_in]
        if not email_site.sitelocker == None:
            sitelocker_ver = email_site.sitelocker
        if not email_site.riddleme == None:
            if not email_site.riddleme.lower() == 'false':
                riddleme_mode = True'''
项目:exit_code_dev    作者:TheCyaniteProject    | 项目源码 | 文件源码
def page_shmail(self):
        global sitelocker_ver
        global riddleme_mode
        global hackable
        hackable = False
        sitelocker_ver = False
        riddleme_mode = False
        tkinter_ui.set_url('http://www.shhmail.net')
        import data.sites.email.email_site as email_site
        importlib.reload(email_site)
        email_site.web_site(tkinter_ui.web_page, tkinter_ui.go_from)
        hackable = [email_site.email_user, email_site.hack_in]
        if email_site.sitelocker is not None:
            sitelocker_ver = email_site.sitelocker
        if email_site.riddleme is not None:
            if not email_site.riddleme.lower() == 'false':
                riddleme_mode = True
项目:labots    作者:SilverRainZ    | 项目源码 | 文件源码
def _unload(self, modname, force = False):
        bot = self._get(modname)
        if not bot:
            logger.warn('"%s" is not loaded', modname)
            return False
        if  not bot.reload and not force:
            logger.warn('"%s" cen not be reloaded', modname)
            return False
        try:
            bot.finalize()
        except Exception as err:
            logger.error('Bot "%s" failed to finalize: %s', bot._name, err)

        self.bots.remove(bot)
        for t in bot.targets:
            self.part_handler(t)
        logger.info('Bot "%s" is unloaded', bot._name)
        return True
项目:bge-logic-nodes-add-on    作者:thepgi    | 项目源码 | 文件源码
def load_nodes_from(abs_dir):
    print("loading project nodes and cells from {}".format(abs_dir))
    dir_file_names = os.listdir(abs_dir)
    py_file_names = [x for x in dir_file_names if x.endswith(".py")]
    for fname in py_file_names:
        mod_name = fname[:-3]
        full_path = os.path.join(abs_dir, fname)
        source = None
        with open(full_path, "r") as f:
            source = f.read()
        if source:
            bge_netlogic = _get_this_module()
            locals = {
                "bge_netlogic": _get_this_module(),
                "__name__": mod_name,
                "bpy": bpy}
            globals = locals
            print("loading... {}".format(mod_name))
            exec(source, locals, globals)
            #TODO: reload source to refresh intermediate compilation?
    pass
项目:pydbvolve    作者:Teamworksapp    | 项目源码 | 文件源码
def test_11_run_migration_bad_command():
    """Verify that run_migration detects a bad command"""
    try:
        os.unlink(TEST_DB_FILE)
    except:
        pass

    rc = pydbvolve.run_migration(TEST_CONFIG_FILE, 'BAD_COMMAND_STRING', 'r1.0.0', True, False)
    assert(rc != 0)

    # test second path (which should not be hit, but you never know...)
    pydbvolve.VALID_ACTIONS.add('BAD_COMMAND_STRING')
    rc = pydbvolve.run_migration(TEST_CONFIG_FILE, 'BAD_COMMAND_STRING', 'r1.0.0', True, False)
    assert(rc != 0)

    importlib.reload(pydbvolve)

    os.unlink(TEST_DB_FILE)
# End test_11_run_migration_bad_command
项目:pydbvolve    作者:Teamworksapp    | 项目源码 | 文件源码
def test_12_run_migration_bad_config():
    """Verify that run_migration detects a bad config"""
    def bad_init_1(*args, **kwargs):
        return None
    def bad_init_2(*args, **kwargs):
        return {'a': 1}

    rc = pydbvolve.run_migration(TEST_CONFIG_FILE + 'bad', 'BAD_COMMAND_STRING', 'r1.0.0', True, False)
    assert(rc != 0)

    pydbvolve.initialize = bad_init_1
    rc = pydbvolve.run_migration(TEST_CONFIG_FILE, 'BAD_COMMAND_STRING', 'r1.0.0', True, False)
    assert(rc != 0)

    pydbvolve.initialize = bad_init_2
    rc = pydbvolve.run_migration(TEST_CONFIG_FILE, 'BAD_COMMAND_STRING', 'r1.0.0', True, False)
    assert(rc != 0)

    importlib.reload(pydbvolve)
# End test_12_run_migration_bad_config
项目:pydbvolve    作者:Teamworksapp    | 项目源码 | 文件源码
def test_15_pre_exec_trap_exception():
    def raise_it(*args, **kwargs):
        raise Exception("Something")

    try:
        os.unlink(TEST_DB_FILE)
    except:
        pass

    pydbvolve.pre_execution = raise_it

    rc = pydbvolve.run_migration(TEST_CONFIG_FILE, 'baseline', 'r1.0.0', True, False)
    assert(rc != 0)

    rc = pydbvolve.run_migration(TEST_CONFIG_FILE, 'baseline', 'r1.0.0', True, True)
    assert(rc != 0)

    importlib.reload(pydbvolve)

    os.unlink(TEST_DB_FILE)
# End test_15_pre_exec_trap_exception
项目:specto    作者:mrknow    | 项目源码 | 文件源码
def patch_reload():
    try:
        import __builtin__ as builtins
    except ImportError:
        import builtins

    if hasattr(builtins, "reload"):
        sys.builtin_orig_reload = builtins.reload
        builtins.reload = patched_reload(sys.builtin_orig_reload)  # @UndefinedVariable
        try:
            import imp
            sys.imp_orig_reload = imp.reload
            imp.reload = patched_reload(sys.imp_orig_reload)  # @UndefinedVariable
        except:
            pass
    else:
        try:
            import importlib
            sys.importlib_orig_reload = importlib.reload  # @UndefinedVariable
            importlib.reload = patched_reload(sys.importlib_orig_reload)  # @UndefinedVariable
        except:
            pass

    del builtins
项目:specto    作者:mrknow    | 项目源码 | 文件源码
def cancel_patches_in_sys_module():
    sys.exc_info = sys.system_exc_info  # @UndefinedVariable
    try:
        import __builtin__ as builtins
    except ImportError:
        import builtins

    if hasattr(sys, "builtin_orig_reload"):
        builtins.reload = sys.builtin_orig_reload

    if hasattr(sys, "imp_orig_reload"):
        import imp
        imp.reload = sys.imp_orig_reload

    if hasattr(sys, "importlib_orig_reload"):
        import importlib
        importlib.reload = sys.importlib_orig_reload

    del builtins
项目:snowballing    作者:JoaoFelipe    | 项目源码 | 文件源码
def load_work_map(year):
    """Load all work from a given year file
    It generates tuples with variable name and Work object

    Doctest:

    .. doctest::

        >>> reload()
        >>> sorted([(work.year, key) for key, work in load_work_map(2015)])
        [(2014, 'murta2014a'), (2015, 'pimentel2015a')]

    (2014, 'murta2014a') appears because it has an alias in 2015
    """
    module = "y{}.py".format(year) if isinstance(year, int) else year
    if module not in WORK_CACHE:
        module = "y9999.py"
    worklist = WORK_CACHE[module]
    for key, work in worklist.__dict__.items():
        if isinstance(work, worklist.Work):
            yield key, work
项目:snowballing    作者:JoaoFelipe    | 项目源码 | 文件源码
def work_by_varname(varname, year=None):
    """Load work by varname

    Doctest:

    .. doctest::

        >>> reload()
        >>> work = work_by_varname('murta2014a')
        >>> work.year
        2014
    """
    if year is None:
        year = int(parse_varname(varname, 2) or -1)
    module = "y{}.py".format(year) if isinstance(year, int) else year
    if module not in WORK_CACHE:
        return
    worklist = WORK_CACHE[module]
    return getattr(worklist, varname, None)
项目:snowballing    作者:JoaoFelipe    | 项目源码 | 文件源码
def load_work_map_all_years():
    """Load all work from all years

    Doctest:

    .. doctest::

        >>> reload()
        >>> sorted([(work.year, key) for key, work in load_work_map_all_years()])
        [(2008, 'freire2008a'), (2014, 'murta2014a'), (2014, 'murta2014a'), (2015, 'pimentel2015a')]

    (2014, 'murta2014a') appears twice because it has an alias in 2015
    """
    years = reversed(sorted(WORK_CACHE.keys()))
    for year in years:
        yield from load_work_map(year)
项目:snowballing    作者:JoaoFelipe    | 项目源码 | 文件源码
def import_submodules(package, recursive=True):
    """Import all submodules of a module, recursively, including subpackages

    Arguments:

    * `package` -- package (name or actual module)

    Keyword arguments:

    * `recursive` -- import modules recursively
    """
    if package is None:
        return {}
    if isinstance(package, str):
        package = importlib.import_module(package)
        importlib.reload(package)
    results = {}
    for loader, name, is_pkg in pkgutil.walk_packages(package.__path__):
        full_name = package.__name__ + '.' + name

        results[full_name] = importlib.import_module(full_name)
        importlib.reload(results[full_name])
        if recursive and is_pkg:
            results.update(import_submodules(full_name))
    return results
项目:taktyk    作者:kosior    | 项目源码 | 文件源码
def process_unimported(self):
        msg = 'Brak modu?u pip!\nNie mo?na zainstalowa?:\n%s'
        msg_dec = 'Wymagane modu?y:\n{}\nChcesz zainstalowa? (T/n)? '
        self.to_import = list(self.unimported)
        modules_text = '\n'.join([' {} - {}'.format(ins, ver) for _, ins, ver in self.unimported])
        if self.try_import('pip', add=False):
            msg_dec = msg_dec.format(modules_text)
            decision = Decision(msg_dec, {'T': {self.install_unimported: (self.unimported,)},
                                          'n': sys.exit})
            decision.run()
            if all(self.import_all(reload=True)):
                logging.info('...ponowne uruchamianie')
                os.execv(sys.executable, ['python'] + sys.argv)
            else:
                logging.critical('Nie uda?o si? zainstalowa? modu?ów.')
                raise SystemExit
        else:
            logging.critical(msg, modules_text)
            raise SystemExit
项目:qudi    作者:Ulm-IQO    | 项目源码 | 文件源码
def loadConfig(self, filename, restart=False):
        """ Load configuration from file.

          @param str filename: path of file to be loaded
        """
        maindir = self.getMainDir()
        configdir = os.path.join(maindir, 'config')
        loadFile = os.path.join(configdir, 'load.cfg')
        if filename.startswith(configdir):
            filename = re.sub(
                '^' + re.escape('/'),
                '',
                re.sub(
                    '^' + re.escape(configdir),
                    '',
                    filename)
                )
        loadData = {'configfile': filename}
        config.save(loadFile, loadData)
        logger.info('Set loaded configuration to {0}'.format(filename))
        if restart:
            logger.info('Restarting Qudi after configuration reload.')
            self.restart()
项目:komlogd    作者:komlog-io    | 项目源码 | 文件源码
def load_entry_points():
    importlib.reload(pkg_resources)
    for ep in pkg_resources.iter_entry_points(group=defaults.PACKAGES_ENTRY_POINT):
        logging.logger.info('loading entry_point: '+str(ep))
        try:
            f = ep.load()
            if asyncio.iscoroutinefunction(f):
                await f()
            elif isinstance(f, types.FunctionType):
                f()
        except (ModuleNotFoundError,SyntaxError):
            logging.logger.error('Error loading package entry point.')
            ex_info=traceback.format_exc().splitlines()
            for line in ex_info:
                logging.logger.error(line)
            return False
        else:
            logging.logger.info('entry_point loaded successfully: '+str(ep))
    return True
项目:switchboard    作者:josefschneider    | 项目源码 | 文件源码
def load_attribute(attribute):
    ''' Loads or reloads the given attribute. For example:

        1) load_attribute('module.submodule.class_name')

            will return the type class_name (but not instantiate it)
            from the module 'module.submodule'

        2) load_attribute('module.submodule.func_name')

            will return the function from that same module. '''

    attribute_name = attribute.split('.')[-1]
    pymodule = '.'.join(attribute.split('.')[:-1])

    if pymodule in sys.modules:
        pymodule_instance = importlib.reload(sys.modules[pymodule])
    else:
        pymodule_instance = importlib.import_module(pymodule)

    # Get the attribute and return it
    return getattr(pymodule_instance, attribute_name)
项目:tensorly    作者:tensorly    | 项目源码 | 文件源码
def set_backend(backend_name):
    """Sets the backend for TensorLy

        The backend will be set as specified and operations will used that backend

    Parameters
    ----------
    backend_name : {'mxnet', 'numpy', 'pytorch'}, default is 'numpy'
    """
    global _BACKEND
    _BACKEND = backend_name

    # reloads tensorly.backend
    importlib.reload(backend)

    # reload from .backend import * (e.g. tensorly.tensor)
    globals().update(
            {fun: getattr(backend, fun) for n in backend.__all__} if hasattr(backend, '__all__') 
            else 
            {k: v for (k, v) in backend.__dict__.items() if not k.startswith('_')
            })
项目:statestream    作者:VolkerFischer    | 项目源码 | 文件源码
def test_python_importlib_reload():
    """Test the python module reload function.
    """
    import statestream.visualization.visualization

    reloaded = False
    try:
        importlib.reload(statestream.visualization.visualization)
        reloaded = True
    except:
        try:
            reload(statestream.visualization.visualization)
            reloaded = True
        except:
            pass
    assert(reloaded), "Error: Unable to reload modules."
项目:wxpythoncookbookcode    作者:driscollis    | 项目源码 | 文件源码
def onReload(self, event):
        """
        Reload the code!
        """
        if self.testFrame:
            self.testFrame.Close()
            try:
                reload(testApp)
            except NameError:
                # reload doesn't exist in Python 3. 
                # Use importlib.reload in Python 3.4+ 
                # or imp.reload in Python 3.0 - 3.3
                import importlib
                importlib.reload(testApp)
            self.showApp()
        else:
            self.testFrame = None
项目:spoonybard    作者:notnownikki    | 项目源码 | 文件源码
def reload(self):
        self.load(self.filename)
项目:spoonybard    作者:notnownikki    | 项目源码 | 文件源码
def load(self, name, force_reload_if_unmanaged=False):
        if name in sys.modules and name not in self.plugins:
            # we're getting an already loaded module, which we has not been
            # loaded through PluginManager, return it from sys.modules and
            # add it to our list
            module = sys.modules[name]
            if force_reload_if_unmanaged:
                importlib.reload(module)
        else:
            module = importlib.import_module(name)
        self.plugins.add(name)
        return module
项目:spoonybard    作者:notnownikki    | 项目源码 | 文件源码
def reload(self):
        self.job_handlers = {}
        for name in self.plugins:
            module = importlib.import_module(name)
            importlib.reload(module)
项目:coa_tools    作者:ndee85    | 项目源码 | 文件源码
def setup_addon_modules(path, package_name):
    """
    Imports and reloads all modules in this addon. 

    path -- __path__ from __init__.py
    package_name -- __name__ from __init__.py
    """
    def get_submodule_names(path = path[0], root = ""):
        module_names = []
        for importer, module_name, is_package in pkgutil.iter_modules([path]):
            if is_package:
                sub_path = os.path.join(path, module_name)
                sub_root = root + module_name + "."
                module_names.extend(get_submodule_names(sub_path, sub_root))
            else: 
                module_names.append(root + module_name)
        return module_names 

    def import_submodules(names):
        modules = []
        for name in names:
            modules.append(importlib.import_module("." + name, package_name))
        return modules

    def reload_modules(modules):
        for module in modules:
            importlib.reload(module)

    names = get_submodule_names()
    modules = import_submodules(names)        
    if reload_event: 
        reload_modules(modules) 
    return modules
项目:python-    作者:secondtonone1    | 项目源码 | 文件源码
def reload(module):
    """**DEPRECATED**

    Reload the module and return it.

    The module must have been successfully imported before.

    """
    return importlib.reload(module)
项目:Blender-power-sequencer    作者:GDquest    | 项目源码 | 文件源码
def setup_addon_modules(path, package_name):
    """
    Imports and reloads all modules in this addon.

    path -- __path__ from __init__.py
    package_name -- __name__ from __init__.py
    """

    def get_submodule_names(path=path[0], root=""):
        module_names = []
        for importer, module_name, is_package in pkgutil.iter_modules([path]):
            if is_package:
                sub_path = path + "\\" + module_name
                sub_root = root + module_name + "."
                module_names.extend(get_submodule_names(sub_path, sub_root))
            else:
                module_names.append(root + module_name)
        return module_names

    def import_submodules(names):
        modules = []
        for name in names:
            modules.append(importlib.import_module("." + name, package_name))
        return modules

    def reload_modules(modules):
        for module in modules:
            importlib.reload(module)

    names = get_submodule_names()
    modules = import_submodules(names)
    if reload_event:
        reload_modules(modules)
    return modules
项目:Blender-WMO-import-export-scripts    作者:WowDevTools    | 项目源码 | 文件源码
def setup_addon_modules(path, package_name, reload):
    """
    Imports and reloads all modules in this addon.

    path -- __path__ from __init__.py
    package_name -- __name__ from __init__.py

    Individual modules can define a __reload_order_index__ property which
    will be used to reload the modules in a specific order. The default is 0.
    """
    def get_submodule_names(path = path[0], root = ""):
        module_names = []
        for importer, module_name, is_package in pkgutil.iter_modules([path]):
            if is_package:
                sub_path = os.path.join(path, module_name)
                sub_root = root + module_name + "."
                module_names.extend(get_submodule_names(sub_path, sub_root))
            else:
                module_names.append(root + module_name)
        return module_names

    def import_submodules(names):
        modules = []
        for name in names:
            modules.append(importlib.import_module("." + name, package_name))
        return modules

    def reload_modules(modules):
        modules.sort(key = lambda module: getattr(module, "__reload_order_index__", 0))
        for module in modules:
            importlib.reload(module)

    names = get_submodule_names()
    modules = import_submodules(names)
    if reload:
        reload_modules(modules)
    return modules
项目:shadowsocksR-b    作者:hao35954514    | 项目源码 | 文件源码
def load(name):
    try:
        obj = __import__(name)
        reload(obj)
        return obj
    except:
        pass

    try:
        import importlib
        obj = importlib.__import__(name)
        importlib.reload(obj)
        return obj
    except:
        pass
项目:zmirror    作者:aploium    | 项目源码 | 文件源码
def reload_zmirror(self, configs_dict=None):
        self.del_temp_var()

        import config
        importlib.reload(config)

        test_config_names = (name for name in dir(self.C) if name[:2] != '__' and name[-2:] != '__')
        for config_name in test_config_names:
            config_value = getattr(self.C, config_name)
            setattr(config, config_name, config_value)

        if configs_dict is not None:
            for config_name, config_value in configs_dict.items():
                setattr(config, config_name, config_value)

        import zmirror.cache_system as cache_system
        import zmirror.zmirror as zmirror
        importlib.reload(cache_system)
        importlib.reload(zmirror)

        zmirror.app.config['TESTING'] = True

        # ?????????, ? del_temp_var() ???
        if hasattr(self.C, "my_host_port"):
            port = getattr(self.C, "my_host_port", None)
            my_host_name = getattr(self.C, "my_host_name", "127.0.0.1")
            if port is not None:
                self.C.my_host_name_no_port = my_host_name
                self.C.my_host_name = self.C.my_host_name_no_port + ":" + str(port)
            else:
                self.C.my_host_name_no_port = my_host_name
        elif hasattr(self.C, "my_host_name"):
            self.C.my_host_name_no_port = self.C.my_host_name

        self.client = zmirror.app.test_client()  # type: FlaskClient
        self.app = zmirror.app  # type: Flask
        self.zmirror = zmirror
项目:youtube    作者:FishyFing    | 项目源码 | 文件源码
def _reload(self, *, cog_name: str):
        """Reloads a module
        Example: reload audio"""
        module = cog_name.strip()
        if "modules." not in module:
            module = "modules." + module

        try:
            self._unload_cog(module, reloading=True)
        except:
            pass

        try:
            self._load_cog(module)
        except CogNotFoundError:
            await ctx.send("That cog cannot be found.")
        except NoSetupError:
            await ctx.send("That cog does not have a setup function.")
        except CogLoadError as e:
            logger.exception(e)
            traceback.print_exc()
            await ctx.send("That cog could not be loaded. Check your"
                           " console or logs for more information.")
        else:
            set_cog(module, True)
            await self.disable_commands()
            await ctx.send("The cog has been reloaded.")
项目:youtube    作者:FishyFing    | 项目源码 | 文件源码
def _load_cog(self, cogname):
        if not self._does_cogfile_exist(cogname):
            raise CogNotFoundError(cogname)
        try:
            mod_obj = importlib.import_module(cogname)
            importlib.reload(mod_obj)
            self.bot.load_extension(mod_obj.__name__)
        except SyntaxError as e:
            raise CogLoadError(*e.args)
        except:
            raise
项目:latplan    作者:guicho271828    | 项目源码 | 文件源码
def test():
    import importlib
    importlib.reload(p)
    configs = p.generate_configs(4)
    puzzles = p.generate_gpu(configs[-30:])
    plot_image(p.batch_unswirl(puzzles)[-1],        "lightsout_twisted_untwisted.png")
    plot_image(p.batch_unswirl(puzzles)[-1].round(),"lightsout_twisted_untwisted__r.png")
    plot_image((p.batch_unswirl(puzzles)[-1]+0.18).round(),        "lightsout_twisted_untwisted__x.png")
项目:MIT-Thesis    作者:alec-heif    | 项目源码 | 文件源码
def test_unbounded_frames(self):
        from unittest.mock import patch
        from pyspark.sql import functions as F
        from pyspark.sql import window
        import importlib

        df = self.spark.range(0, 3)

        def rows_frame_match():
            return "ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING" in df.select(
                F.count("*").over(window.Window.rowsBetween(-sys.maxsize, sys.maxsize))
            ).columns[0]

        def range_frame_match():
            return "RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING" in df.select(
                F.count("*").over(window.Window.rangeBetween(-sys.maxsize, sys.maxsize))
            ).columns[0]

        with patch("sys.maxsize", 2 ** 31 - 1):
            importlib.reload(window)
            self.assertTrue(rows_frame_match())
            self.assertTrue(range_frame_match())

        with patch("sys.maxsize", 2 ** 63 - 1):
            importlib.reload(window)
            self.assertTrue(rows_frame_match())
            self.assertTrue(range_frame_match())

        with patch("sys.maxsize", 2 ** 127 - 1):
            importlib.reload(window)
            self.assertTrue(rows_frame_match())
            self.assertTrue(range_frame_match())

        importlib.reload(window)
项目:aquests    作者:hansroh    | 项目源码 | 文件源码
def importer (directory, libpath, module = None):
    fn = not libpath.endswith (".py") and libpath + ".py" or libpath
    modpath = os.path.join (directory, fn)
    hname = fn.split (".")[0]
    p = directory.replace ("\\", "/")
    if p.find (":") !=- 1:
        p = "/" + p.replace (":", "")
    while 1:
        if "skitai.mounted." + hname in sys.modules:                
            p, l = os.path.split (p)
            if not l:
                raise SystemError ('module %s already imported, use reload')
            hname = l + "." + hname
        else:
            hname = "skitai.mounted." + hname
            break

    loader = importlib.machinery.SourceFileLoader(hname, modpath)
    mod = loader.load_module ()

    return mod, mod.__file__
项目:micromasters    作者:mitodl    | 项目源码 | 文件源码
def reload_settings(self):
        """
        Reload settings module with cleanup to restore it.

        Returns:
            dict: dictionary of the newly reloaded settings ``vars``
        """
        importlib.reload(sys.modules['micromasters.settings'])
        # Restore settings to original settings after test
        self.addCleanup(importlib.reload, sys.modules['micromasters.settings'])
        return vars(sys.modules['micromasters.settings'])
项目:sga-lti    作者:mitodl    | 项目源码 | 文件源码
def reload_settings(self):
        """
        Reload settings module with cleanup to restore it.

        Returns:
            dict: dictionary of the newly reloaded settings ``vars``
        """
        importlib.reload(sys.modules['sga_lti.settings'])
        # Restore settings to original settings after test
        self.addCleanup(importlib.reload, sys.modules['sga_lti.settings'])
        return vars(sys.modules['sga_lti.settings'])
项目:ivaochdoc    作者:ivaoch    | 项目源码 | 文件源码
def reload(module):
    """**DEPRECATED**

    Reload the module and return it.

    The module must have been successfully imported before.

    """
    return importlib.reload(module)
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def reset_all(*, reload_scripts=False):
    """
    Sets the addon state based on the user preferences.
    """
    import sys

    # initializes addons_fake_modules
    modules_refresh()

    # RELEASE SCRIPTS: official scripts distributed in Blender releases
    paths_list = paths()

    for path in paths_list:
        _bpy.utils._sys_path_ensure(path)
        for mod_name, mod_path in _bpy.path.module_names(path):
            is_enabled, is_loaded = check(mod_name)

            # first check if reload is needed before changing state.
            if reload_scripts:
                import importlib
                mod = sys.modules.get(mod_name)
                if mod:
                    importlib.reload(mod)

            if is_enabled == is_loaded:
                pass
            elif is_enabled:
                enable(mod_name)
            elif is_loaded:
                print("\taddon_utils.reset_all unloading", mod_name)
                disable(mod_name)
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def register():
    ####################
    # F8 - key
    import importlib
    importlib.reload(ms3d_ui)
    # F8 - key
    ####################

    ms3d_ui.register()

    register_module(__name__)
    INFO_MT_file_export.append(Ms3dExportOperator.menu_func)
    INFO_MT_file_import.append(Ms3dImportOperator.menu_func)