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

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

项目:Modeling-Cloth    作者:the3dadvantage    | 项目源码 | 文件源码
def collision_series(paperback=True, kindle=True):
    import webbrowser
    import imp
    if paperback:    
        webbrowser.open("https://www.createspace.com/6043857")
        imp.reload(webbrowser)
        webbrowser.open("https://www.createspace.com/7164863")
        return
    if kindle:
        webbrowser.open("https://www.amazon.com/Resolve-Immortal-Flesh-Collision-Book-ebook/dp/B01CO3MBVQ")
        imp.reload(webbrowser)
        webbrowser.open("https://www.amazon.com/Formulacrum-Collision-Book-Rich-Colburn-ebook/dp/B0711P744G")
        return
    webbrowser.open("https://www.paypal.com/donate/?token=G1UymFn4CP8lSFn1r63jf_XOHAuSBfQJWFj9xjW9kWCScqkfYUCdTzP-ywiHIxHxYe7uJW&country.x=US&locale.x=US")

# ============================================================================================
项目:scarlett_os    作者:bossjones    | 项目源码 | 文件源码
def player_unit_mocker_stopall(mocker):
    print('Called [setup]: mocker.stopall()')
    mocker.stopall()
    print('Called [setup]: imp.reload(player)')
    imp.reload(player)
    yield mocker
    print('Called [teardown]: mocker.stopall()')
    mocker.stopall()
    print('Called [setup]: imp.reload(player)')
    imp.reload(player)


# pylint: disable=R0201
# pylint: disable=C0111
# pylint: disable=C0123
# pylint: disable=C0103
# pylint: disable=W0212
# pylint: disable=W0621
# pylint: disable=W0612
项目:sequana    作者:sequana    | 项目源码 | 文件源码
def test_lazy(mocker):
    import sys
    import sequana.lazy as lazy
    import sequana.lazyimports as lazyimports
    import imp

    li = lazyimports.LazyImport('os')
    li
    # we import sphinx now, and reload the module so enter in the case where
    # sphinx is loaded
    import sphinx
    imp.reload(lazyimports)
    try:
        assert lazy.enabled() == False
        li = lazyimports.LazyImport("os")
        li.path
    except Exception as err:
        raise(err)
    finally:
        #del sys.modules['sphinx']
        #imp.reload(lazyimports)
        #assert lazy.enabled() == True
        pass
项目:locasploit    作者:lightfaith    | 项目源码 | 文件源码
def load_modules():
    """ Import modules from source/modules/ folder """
    lib.module_objects = []
    lib.modules = {}
    module_names = [x[:-3] for x in os.listdir('source/modules') if x[0]!='_' and x[-3:] == '.py']

    # import/reimport modules
    for m in module_names:
        if 'source.modules.' + m in sys.modules:
            imp.reload(sys.modules['source.modules.' + m]) # TODO deprecated?
        else:
            importlib.import_module('source.modules.' + m)

    # initialize modules dictionary
    for v in lib.module_objects:
        if v.name in lib.modules:
            log.warn('Duplicit module %s.' % (v.name))
        lib.modules[v.name] = v 

    log.info('%d modules loaded.' % (len(lib.modules)))
项目:macos-st-packages    作者:zce    | 项目源码 | 文件源码
def undo_me(self, view):
        view.settings().erase('prevent_detect')
        view.run_command('undo')
        # restore folded regions
        regions = view.settings().get('folded_regions')
        if regions:
            view.settings().erase('folded_regions')
            folded = [sublime.Region(int(region[0]), int(region[1])) for region in regions]
            view.fold(folded)
        vp = view.settings().get('viewport_position')
        if vp:
            view.settings().erase('viewport_position')
            view.set_viewport_position((vp[0], vp[1]), False)
        # st3 will reload file immediately
        if view.settings().get('revert_to_scratch') or (ST3 and not get_setting(view, 'lazy_reload')):
            view.set_scratch(True)
项目:ozelot    作者:trycs    | 项目源码 | 文件源码
def test_value_override(self):
        """Test overriding a default value

        The project config of the logging module sets the log level to 'DEBUG' and defines some other testing values.
        """
        # reload the config module to make sure we get a fresh instance (nose shares module state between tests)
        imp.reload(config)

        self.assertEquals(config.LOG_LEVEL, logging.DEBUG)
        # noinspection PyUnresolvedReferences
        self.assertEquals(config.LOG_LEVEL_DEFAULT, logging.INFO)

        # this variable does not exist originally and does not have a backup of the default value
        # noinspection PyUnresolvedReferences
        self.assertEquals(config.TESTING_VARIABLE, 123)

        # # we could test for 'TESTING_VARIABLE_DEFAULT' not being set; however, the 'reload' statement
        # # above causes the testing variable to also be copied to 'TESTING_VARIABLE_DEFAULT'
        # self.assertIsNone(getattr(config, 'TESTING_VARIABLE_DEFAULT', None))
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def filename_and_mtime(self, module):
        if not hasattr(module, '__file__') or module.__file__ is None:
            return None, None

        if getattr(module, '__name__', None) in ['__mp_main__', '__main__']:
            # we cannot reload(__main__) or reload(__mp_main__)
            return None, None

        filename = module.__file__
        path, ext = os.path.splitext(filename)

        if ext.lower() == '.py':
            py_filename = filename
        else:
            try:
                py_filename = openpy.source_from_cache(filename)
            except ValueError:
                return None, None

        try:
            pymtime = os.stat(py_filename).st_mtime
        except OSError:
            return None, None

        return py_filename, pymtime
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def reload_extension(self, module_str):
        """Reload an IPython extension by calling reload.

        If the module has not been loaded before,
        :meth:`InteractiveShell.load_extension` is called. Otherwise
        :func:`reload` is called and then the :func:`load_ipython_extension`
        function of the module, if it exists is called.
        """
        from IPython.utils.syspathcontext import prepended_to_syspath

        if (module_str in self.loaded) and (module_str in sys.modules):
            self.unload_extension(module_str)
            mod = sys.modules[module_str]
            with prepended_to_syspath(self.ipython_extension_dir):
                reload(mod)
            if self._call_load_ipython_extension(mod):
                self.loaded.add(module_str)
        else:
            self.load_extension(module_str)
项目: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
项目:FT.Client    作者:aldmbmtl    | 项目源码 | 文件源码
def updateInstall():
    """
    Updates the existing install of the HFX pipeline.
    """
    exec urllib.urlopen('https://raw.githubusercontent.com/aldmbmtl/FT.Client/master/installer.py').read()

    # force reload FT
    imp.reload(FloatingTools)

# load settings for the toolbox
项目:hookshub    作者:gisce    | 项目源码 | 文件源码
def reload_hooks():
    # Update working set before using it
    import imp
    import pkg_resources
    imp.reload(pkg_resources)
    # Import plugin managers after reloading pkg_resources
    from hookshub.plugins import plugins
    from pkg_resources import working_set
    logger = logging.getLogger()
    for entrypoint in working_set.iter_entry_points('hookshub.plugins'):
        try:
            plugin = entrypoint.load()
        except Exception as e:
            logger.error('Could not load plugin {}:\n{}'.format(
                entrypoint, e
            ))
        else:
            plugins.register(plugin)
项目:Opencv_learning    作者:wjb711    | 项目源码 | 文件源码
def try1():
    global name
    global chat
    name="??"
    chat="??"
    try:
        print ('try',driver)
        imp.reload(weixin_action)
        print ('reload done')
        weixin_action.test(name,chat)
        print ('a2 test done')
    except:
        print ('except')
        imp.reload(weixin_action)
        time.sleep(3)
        try1()
    print ('try1 done')
项目:Opencv_learning    作者:wjb711    | 项目源码 | 文件源码
def try1():
    global name
    global chat
    name="??"
    chat="??"
    try:
        print ('try',driver)
        imp.reload(weixin_action)
        print ('reload done')
        weixin_action.test(name,chat)
        print ('a2 test done')
    except:
        print ('except')
        imp.reload(weixin_action)
        time.sleep(3)
        try1()
    print ('try1 done')
项目:SlackBuilds    作者:montagdude    | 项目源码 | 文件源码
def include_dirs_hook():
        if sys.version_info[0] >= 3:
            import builtins
            if hasattr(builtins, '__NUMPY_SETUP__'):
                del builtins.__NUMPY_SETUP__
            import imp
            import numpy
            imp.reload(numpy)
        else:
            import __builtin__
            if hasattr(__builtin__, '__NUMPY_SETUP__'):
                del __builtin__.__NUMPY_SETUP__
            import numpy
            reload(numpy)

        ext = Extension('test', [])
        ext.include_dirs.append(numpy.get_include())
        if not has_include_file(
                ext.include_dirs, os.path.join("numpy", "arrayobject.h")):
            warnings.warn(
                "The C headers for numpy could not be found. "
                "You may need to install the development package")

        return [numpy.get_include()]
项目: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
项目:editolido    作者:flyingeek    | 项目源码 | 文件源码
def reload_editolido(install_dir, name='editolido'):
    try:
        from importlib import reload
    except ImportError:
        from imp import reload
    queue = []
    for module in sys.modules.values():
        try:
            if os.path.realpath(module.__file__).startswith(
                    os.path.join(install_dir, name) + '/'):  # pragma no cover
                if module.__name__ == name:
                    queue.append(module)
                else:
                    raise ImportError
        except AttributeError:
            pass
        except ImportError:  # pragma no cover
            logger.info('deleting module %s' % module.__name__)
            del sys.modules[module.__name__]
    for module in queue:  # pragma no cover
        reload(module)
        logger.info('Reloaded %s' % module.__name__)
项目:EasyClangComplete    作者:niosus    | 项目源码 | 文件源码
def reload_once(prefix):
        """Reload all modules once."""
        try_counter = 0
        try:
            for name, module in sys.modules.items():
                if name.startswith(prefix):
                    log.debug("reloading module: '%s'", name)
                    imp.reload(module)
        except OSError as e:
            if try_counter >= Reloader.MAX_RELOAD_TRIES:
                log.fatal("Too many tries to reload and no success. Fail.")
                return
            try_counter += 1
            log.error("Received an error: %s on try %s. Try again.",
                      e, try_counter)
            Reloader.reload_once(prefix)
项目:client    作者:wandb    | 项目源码 | 文件源码
def test_push_dirty_git(runner, monkeypatch):
    with runner.isolated_filesystem():
        os.mkdir('wandb')

        # If the test was run from a directory containing .wandb, then __stage_dir__
        # was '.wandb' when imported by api.py, reload to fix. UGH!
        reload(wandb)
        repo = git_repo()
        open("foo.txt", "wb").close()
        repo.repo.index.add(["foo.txt"])
        monkeypatch.setattr(cli, 'api', wandb_api.Api({'project': 'test'}))
        cli.api._settings['git_tag'] = True
        result = runner.invoke(
            cli.push, ["test", "foo.txt", "-p", "test", "-m", "Dirty"])
        print(result.output)
        print(result.exception)
        print(traceback.print_tb(result.exc_info[2]))
        assert result.exit_code == 1
        assert "You have un-committed changes." in result.output
项目:client    作者:wandb    | 项目源码 | 文件源码
def test_init_new_login(runner, empty_netrc, local_netrc, request_mocker, query_projects, query_viewer):
    query_viewer(request_mocker)
    query_projects(request_mocker)
    with runner.isolated_filesystem():
        # If the test was run from a directory containing .wandb, then __stage_dir__
        # was '.wandb' when imported by api.py, reload to fix. UGH!
        reload(wandb)
        result = runner.invoke(cli.init, input="%s\nvanpelt" % DUMMY_API_KEY)
        print('Output: ', result.output)
        print('Exception: ', result.exception)
        print('Traceback: ', traceback.print_tb(result.exc_info[2]))
        assert result.exit_code == 0
        with open("netrc", "r") as f:
            generatedNetrc = f.read()
        with open("wandb/settings", "r") as f:
            generatedWandb = f.read()
        assert DUMMY_API_KEY in generatedNetrc
        assert "test_model" in generatedWandb
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
def filename_and_mtime(self, module):
        if not hasattr(module, '__file__') or module.__file__ is None:
            return None, None

        if getattr(module, '__name__', None) == '__main__':
            # we cannot reload(__main__)
            return None, None

        filename = module.__file__
        path, ext = os.path.splitext(filename)

        if ext.lower() == '.py':
            py_filename = filename
        else:
            try:
                py_filename = openpy.source_from_cache(filename)
            except ValueError:
                return None, None

        try:
            pymtime = os.stat(py_filename).st_mtime
        except OSError:
            return None, None

        return py_filename, pymtime
项目:DjangoCMS    作者:farhan711    | 项目源码 | 文件源码
def debug_server_restart(**kwargs):
    from cms.appresolver import clear_app_resolvers
    if 'runserver' in sys.argv or 'server' in sys.argv:
        clear_app_resolvers()
        clear_url_caches()
        import cms.urls
        try:
            reload(cms.urls)
        except NameError: #python3
            from imp import reload
            reload(cms.urls)
    if not 'test' in sys.argv:
        msg = 'Application url changed and urls_need_reloading signal fired. ' \
              'Please reload the urls.py or restart the server.\n'
        styles = color_style()
        msg = styles.NOTICE(msg)
        sys.stderr.write(msg)
项目:SmartVHDL    作者:TheClams    | 项目源码 | 文件源码
def plugin_loaded():
    imp.reload(vhdl_util)
    imp.reload(sublime_util)
    # Ensure the preference settings are properly reloaded when changed
    global pref_settings
    pref_settings = sublime.load_settings('Preferences.sublime-settings')
    pref_settings.clear_on_change('reload')
    pref_settings.add_on_change('reload',plugin_loaded)
    # Ensure the VHDL settings are properly reloaded when changed
    global vhdl_settings
    vhdl_settings = sublime.load_settings('VHDL.sublime-settings')
    vhdl_settings.clear_on_change('reload')
    vhdl_settings.add_on_change('reload',plugin_loaded)
    global tooltip_flag
    if vhdl_settings.get('vhdl.tooltip_hide_on_move',True):
        tooltip_flag = sublime.HIDE_ON_MOUSE_MOVE_AWAY
    else:
        tooltip_flag = 0
    init_css()
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
def test_numpy_reloading():
    # gh-7844. Also check that relevant globals retain their identity.
    import numpy as np
    import numpy._globals

    _NoValue = np._NoValue
    VisibleDeprecationWarning = np.VisibleDeprecationWarning
    ModuleDeprecationWarning = np.ModuleDeprecationWarning

    reload(np)
    assert_(_NoValue is np._NoValue)
    assert_(ModuleDeprecationWarning is np.ModuleDeprecationWarning)
    assert_(VisibleDeprecationWarning is np.VisibleDeprecationWarning)

    assert_raises(RuntimeError, reload, numpy._globals)
    reload(np)
    assert_(_NoValue is np._NoValue)
    assert_(ModuleDeprecationWarning is np.ModuleDeprecationWarning)
    assert_(VisibleDeprecationWarning is np.VisibleDeprecationWarning)
项目:kytos    作者:kytos    | 项目源码 | 文件源码
def test_old_handler_filter():
        """Should not log harmless werkzeug "session is disconnected" msg.

        The filter should be added to all root handlers, even the ones that
        already existed before importing the "logs" module.

        Message based on the log output that ends with traceback plaintext as
        seen in lib/python3.6/site-packages/werkzeug/serving.py:225 of
        Werkzeug==0.12.1:

            - logger name: werkzeug
            - level: ERROR
            - only argument: ends with "KeyError: 'Session is disconnected'"
        """
        old_handler = Mock()
        old_handler.filters = []

        logging.root.addHandler(old_handler)
        old_handler.addFilter.assert_not_called()
        # Importing the module should add the filter to existent root handlers.
        imp.reload(logs)
        old_handler.addFilter.assert_called_once_with(
            logs.LogManager.filter_session_disconnected)

        logging.root.removeHandler(old_handler)
项目:peda-arm    作者:alset0326    | 项目源码 | 文件源码
def main():
    global invoke
    plugins = [i[:-3] for i in os.listdir(os.path.dirname(__file__)) if
               i.startswith('v8_plugin_') and i.endswith('.py')]
    plugins.sort(reverse=True)

    for plugin in plugins:
        if plugin in modules:
            module = reload(modules.get(plugin))
            invoke = module.invoke
            return

    prompt = '\n\t'.join(['[%d] %s' % (index, value) for index, value in enumerate(plugins)])
    prompt = 'Supported Version:\n\t%s\nPlease choose one [Default: 0]: ' % prompt
    try:
        choose = int(input(prompt))
        if choose >= len(plugins):
            raise RuntimeError
    except:
        print('Choosing default 0')
        choose = 0
    module = __import__(plugins[choose])
    invoke = module.invoke
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
def test_numpy_reloading():
    # gh-7844. Also check that relevant globals retain their identity.
    import numpy as np
    import numpy._globals

    _NoValue = np._NoValue
    VisibleDeprecationWarning = np.VisibleDeprecationWarning
    ModuleDeprecationWarning = np.ModuleDeprecationWarning

    reload(np)
    assert_(_NoValue is np._NoValue)
    assert_(ModuleDeprecationWarning is np.ModuleDeprecationWarning)
    assert_(VisibleDeprecationWarning is np.VisibleDeprecationWarning)

    assert_raises(RuntimeError, reload, numpy._globals)
    reload(np)
    assert_(_NoValue is np._NoValue)
    assert_(ModuleDeprecationWarning is np.ModuleDeprecationWarning)
    assert_(VisibleDeprecationWarning is np.VisibleDeprecationWarning)
项目:GSM-scanner    作者:yosriayed    | 项目源码 | 文件源码
def test_reload_is_same(self, testdir):
        # A file that will be picked up during collecting.
        testdir.tmpdir.join("file.py").ensure()
        testdir.tmpdir.join("pytest.ini").write(py.std.textwrap.dedent("""
            [pytest]
            python_files = *.py
        """))

        testdir.makepyfile(test_fun="""
            import sys
            try:
                from imp import reload
            except ImportError:
                pass

            def test_loader():
                import file
                assert sys.modules["file"] is reload(file)
            """)
        result = testdir.runpytest('-s')
        result.stdout.fnmatch_lines([
            "* 1 passed*",
        ])
项目:blender    作者:gastrodia    | 项目源码 | 文件源码
def filename_and_mtime(self, module):
        if not hasattr(module, '__file__') or module.__file__ is None:
            return None, None

        if getattr(module, '__name__', None) == '__main__':
            # we cannot reload(__main__)
            return None, None

        filename = module.__file__
        path, ext = os.path.splitext(filename)

        if ext.lower() == '.py':
            py_filename = filename
        else:
            try:
                py_filename = openpy.source_from_cache(filename)
            except ValueError:
                return None, None

        try:
            pymtime = os.stat(py_filename).st_mtime
        except OSError:
            return None, None

        return py_filename, pymtime
项目:yatta_reader    作者:sound88    | 项目源码 | 文件源码
def filename_and_mtime(self, module):
        if not hasattr(module, '__file__') or module.__file__ is None:
            return None, None

        if getattr(module, '__name__', None) in ['__mp_main__', '__main__']:
            # we cannot reload(__main__) or reload(__mp_main__)
            return None, None

        filename = module.__file__
        path, ext = os.path.splitext(filename)

        if ext.lower() == '.py':
            py_filename = filename
        else:
            try:
                py_filename = openpy.source_from_cache(filename)
            except ValueError:
                return None, None

        try:
            pymtime = os.stat(py_filename).st_mtime
        except OSError:
            return None, None

        return py_filename, pymtime
项目:yatta_reader    作者:sound88    | 项目源码 | 文件源码
def reload_extension(self, module_str):
        """Reload an IPython extension by calling reload.

        If the module has not been loaded before,
        :meth:`InteractiveShell.load_extension` is called. Otherwise
        :func:`reload` is called and then the :func:`load_ipython_extension`
        function of the module, if it exists is called.
        """
        from IPython.utils.syspathcontext import prepended_to_syspath

        if (module_str in self.loaded) and (module_str in sys.modules):
            self.unload_extension(module_str)
            mod = sys.modules[module_str]
            with prepended_to_syspath(self.ipython_extension_dir):
                reload(mod)
            if self._call_load_ipython_extension(mod):
                self.loaded.add(module_str)
        else:
            self.load_extension(module_str)
项目:deb-python-cassandra-driver    作者:openstack    | 项目源码 | 文件源码
def eventlet_un_patch_all():
    """
    A method to unpatch eventlet monkey patching used for the reactor tests
    """

    # These are the modules that are loaded by eventlet we reload them all
    modules_to_unpatch = [os, select, socket, thread, time, Queue, threading, ssl, __builtin__]
    for to_unpatch in modules_to_unpatch:
        reload(to_unpatch)
项目:deb-python-cassandra-driver    作者:openstack    | 项目源码 | 文件源码
def restore_saved_module(module):
    reload(module)
    del eventlet.patcher.already_patched[module.__name__]
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def reload(some_module):
        import imp
        imp.reload(some_module)
        return(some_module)
项目:grammalecte    作者:seeschloss    | 项目源码 | 文件源码
def _loadConfig (self):
        try:
            if sys.version_info.major == 3:
                imp.reload(tf_options)
            else:
                reload(tf_options)
            self._setConfig(tf_options.dOpt)
        except:
            traceback.print_exc()
项目:deadc0debot    作者:De4dc0de    | 项目源码 | 文件源码
def reimport(id): #Reload the definitins file. Disable this in config.py
    if(configfile.updates):
        try:
            try:
                os.system("mv handlefile.py handlefile.py.bak; rm handlefile.pyc")
            except:
                pass
            if(configfile.beta):
                os.system("curl https://raw.githubusercontent.com/De4dc0de/deadc0debot/master/handlefileedit.py?random=" + randomword(10) + " --output handlefile.py")
            else:
                os.system("curl https://raw.githubusercontent.com/De4dc0de/deadc0debot/master/handlefile.py?random=" + randomword(10) + " --output handlefile.py")
            try:
                reload(handlefile)
            except:
                import imp
                imp.reload(handlefile)
            print("reloaded")
            bot.sendMessage(id, "done")
        except:
            try:
                os.system("mv handlefile.py.bak handlefile.py; rm handlefile.pyc")
            except:
                pass
            try:
                reload(handlefile)
            except:
                import imp
                imp.reload(handlefile)
            bot.sendMessage(id, "Update failed. Loaded Backup")
项目:deadc0debot    作者:De4dc0de    | 项目源码 | 文件源码
def handle(msg): #Wrapper for the outsourced and more advanced handle function
    try:
        handlefile.handle(msg, bot, reimport)
    except:
        os.system("mv handlefile.py.bak handlefile.py; rm handlefile.pyc")
        try:
            reload(handlefile)
        except:
            import imp
            imp.reload(handlefile)
        bot.sendMessage(msg["chat"]["id"], "Launch failed. Loaded Backup. Kick the Bot at the next Failure")
项目:scarlett_os    作者:bossjones    | 项目源码 | 文件源码
def player_mocker_stopall(mocker):
    "Stop previous mocks, yield mocker plugin obj, then stopall mocks again"
    print('Called [setup]: mocker.stopall()')
    mocker.stopall()
    print('Called [setup]: imp.reload(threadmanager)')
    imp.reload(player)
    yield mocker
    print('Called [teardown]: mocker.stopall()')
    mocker.stopall()
    print('Called [setup]: imp.reload(threadmanager)')
    imp.reload(player)
项目:scarlett_os    作者:bossjones    | 项目源码 | 文件源码
def listener_mocker_stopall(mocker):
    "Stop previous mocks, yield mocker plugin obj, then stopall mocks again"
    print('Called [setup]: mocker.stopall()')
    mocker.stopall()
    print('Called [setup]: imp.reload(threadmanager)')
    imp.reload(listener)
    yield mocker
    print('Called [teardown]: mocker.stopall()')
    mocker.stopall()
    print('Called [setup]: imp.reload(threadmanager)')
    imp.reload(listener)

# source: test_signal.py in pygobject
项目:scarlett_os    作者:bossjones    | 项目源码 | 文件源码
def threadmanager_unit_mocker_stopall(mocker):
    "Stop previous mocks, yield mocker plugin obj, then stopall mocks again"
    print('Called [setup]: mocker.stopall()')
    mocker.stopall()
    print('Called [setup]: imp.reload(threadmanager)')
    imp.reload(threadmanager)
    yield mocker
    print('Called [teardown]: mocker.stopall()')
    mocker.stopall()
    print('Called [setup]: imp.reload(threadmanager)')
    imp.reload(threadmanager)
项目:scarlett_os    作者:bossjones    | 项目源码 | 文件源码
def commands_unit_mocker_stopall(mocker):
    "Stop previous mocks, yield mocker plugin obj, then stopall mocks again"
    print('Called [setup]: mocker.stopall()')
    mocker.stopall()
    print('Called [setup]: imp.reload(player)')
    imp.reload(commands)
    yield mocker
    print('Called [teardown]: mocker.stopall()')
    mocker.stopall()
    print('Called [setup]: imp.reload(player)')
    imp.reload(commands)
项目:scarlett_os    作者:bossjones    | 项目源码 | 文件源码
def deps_mocker_stopall(mocker):
    "Stop previous mocks, yield mocker plugin obj, then stopall mocks again"
    print('Called [setup]: mocker.stopall()')
    mocker.stopall()
    print('Called [setup]: imp.reload(deps)')
    imp.reload(deps)
    yield mocker
    print('Called [teardown]: mocker.stopall()')
    mocker.stopall()
    print('Called [setup]: imp.reload(deps)')
    imp.reload(deps)
项目:scarlett_os    作者:bossjones    | 项目源码 | 文件源码
def encoding_mocker_stopall(mocker):
    "Stop previous mocks, yield mocker plugin obj, then stopall mocks again"
    print('Called [setup]: mocker.stopall()')
    mocker.stopall()
    print('Called [setup]: imp.reload(encoding)')
    imp.reload(encoding)
    yield mocker
    print('Called [teardown]: mocker.stopall()')
    mocker.stopall()
    print('Called [setup]: imp.reload(encoding)')
    imp.reload(encoding)

# ipdb> str(bytestr)
# "b'[Errno 98] Adresse d\\xe9j\\xe0 utilis\\xe9e'"
项目:scarlett_os    作者:bossjones    | 项目源码 | 文件源码
def simple_config_unit_mocker_stopall(mocker):
    "Stop previous mocks, yield mocker plugin obj, then stopall mocks again"
    print('Called [setup]: mocker.stopall()')
    mocker.stopall()
    print('Called [setup]: imp.reload(simple_config)')
    imp.reload(simple_config)
    yield mocker
    print('Called [teardown]: mocker.stopall()')
    mocker.stopall()
    print('Called [setup]: imp.reload(simple_config)')
    imp.reload(simple_config)
项目:scarlett_os    作者:bossjones    | 项目源码 | 文件源码
def config_unit_mocker_stopall(mocker):
    "Stop previous mocks, yield mocker plugin obj, then stopall mocks again"
    print('Called [setup]: mocker.stopall()')
    mocker.stopall()
    print('Called [setup]: imp.reload(player)')
    imp.reload(smart_config)
    yield mocker
    print('Called [teardown]: mocker.stopall()')
    mocker.stopall()
    print('Called [setup]: imp.reload(player)')
    imp.reload(smart_config)
项目:scarlett_os    作者:bossjones    | 项目源码 | 文件源码
def config_unit_mocker_stopall(mocker):
    "Stop previous mocks, yield mocker plugin obj, then stopall mocks again"
    print('Called [setup]: mocker.stopall()')
    mocker.stopall()
    print('Called [setup]: imp.reload(player)')
    imp.reload(config)
    yield mocker
    print('Called [teardown]: mocker.stopall()')
    mocker.stopall()
    print('Called [setup]: imp.reload(player)')
    imp.reload(config)
项目:OSPTF    作者:xSploited    | 项目源码 | 文件源码
def reload(self, module):
    if module in sys.modules:
      try:
        from imp import reload
      except ImportError:
        pass # builtin in py2k
      reload(sys.modules[module])
      return "reload succeeded."
    return "no reload performed."
项目:filefinder2    作者:asmodehn    | 项目源码 | 文件源码
def reload(module):
        """Reload the module and return it.

        The module must have been successfully imported before.

        """
        if not module or not isinstance(module, types.ModuleType):
            raise TypeError("reload() argument must be a module")
        try:
            name = module.__spec__.name
        except AttributeError:
            name = module.__name__

        if sys.modules.get(name) is not module:
            msg = "module {} not in sys.modules"
            raise _ImportError(msg.format(name), name=name)
        if name in _RELOADING:
            return _RELOADING[name]
        _RELOADING[name] = module
        try:
            reload(module)

            # The module may have replaced itself in sys.modules!
            return sys.modules[name]
        finally:
            try:
                del _RELOADING[name]
            except KeyError:
                pass
项目:watchmen    作者:lycclsltt    | 项目源码 | 文件源码
def test_issue_9(self):
        """ sets DeprecationWarning in Python 2.6 """
        try:
            reload(pymysql)
        except DeprecationWarning:
            self.fail()
项目:touch-pay-client    作者:HackPucBemobi    | 项目源码 | 文件源码
def test_issue_9(self):
        """ sets DeprecationWarning in Python 2.6 """
        try:
            reload(pymysql)
        except DeprecationWarning:
            self.fail()