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

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

项目: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
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
def reloadAll(prefix=None, debug=False):
    """Automatically reload everything whose __file__ begins with prefix.
    - Skips reload if the file has not been updated (if .pyc is newer than .py)
    - if prefix is None, checks all loaded modules
    """
    failed = []
    changed = []
    for modName, mod in list(sys.modules.items()):  ## don't use iteritems; size may change during reload
        if not inspect.ismodule(mod):
            continue
        if modName == '__main__':
            continue

        ## Ignore if the file name does not start with prefix
        if not hasattr(mod, '__file__') or os.path.splitext(mod.__file__)[1] not in ['.py', '.pyc']:
            continue
        if prefix is not None and mod.__file__[:len(prefix)] != prefix:
            continue

        ## ignore if the .pyc is newer than the .py (or if there is no pyc or py)
        py = os.path.splitext(mod.__file__)[0] + '.py'
        pyc = py + 'c'
        if py not in changed and os.path.isfile(pyc) and os.path.isfile(py) and os.stat(pyc).st_mtime >= os.stat(py).st_mtime:
            #if debug:
                #print "Ignoring module %s; unchanged" % str(mod)
            continue
        changed.append(py)  ## keep track of which modules have changed to insure that duplicate-import modules get reloaded.

        try:
            reload(mod, debug=debug)
        except:
            printExc("Error while reloading module %s, skipping\n" % mod)
            failed.append(mod.__name__)

    if len(failed) > 0:
        raise Exception("Some modules failed to reload: %s" % ', '.join(failed))
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
def updateFunction(old, new, debug, depth=0, visited=None):
    #if debug and depth > 0:
        #print "    -> also updating previous version", old, " -> ", new

    old.__code__ = new.__code__
    old.__defaults__ = new.__defaults__

    if visited is None:
        visited = []
    if old in visited:
        return
    visited.append(old)

    ## finally, update any previous versions still hanging around..
    if hasattr(old, '__previous_reload_version__'):
        maxDepth = updateFunction(old.__previous_reload_version__, new, debug, depth=depth+1, visited=visited)
    else:
        maxDepth = depth

    ## We need to keep a pointer to the previous version so we remember to update BOTH
    ## when the next reload comes around.
    if depth == 0:
        new.__previous_reload_version__ = old
    return maxDepth



## For classes:
##  1) find all instances of the old class and set instance.__class__ to the new class
##  2) update all old class methods to use code from the new class methods
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
def reloadAll(prefix=None, debug=False):
    """Automatically reload everything whose __file__ begins with prefix.
    - Skips reload if the file has not been updated (if .pyc is newer than .py)
    - if prefix is None, checks all loaded modules
    """
    failed = []
    changed = []
    for modName, mod in list(sys.modules.items()):  ## don't use iteritems; size may change during reload
        if not inspect.ismodule(mod):
            continue
        if modName == '__main__':
            continue

        ## Ignore if the file name does not start with prefix
        if not hasattr(mod, '__file__') or os.path.splitext(mod.__file__)[1] not in ['.py', '.pyc']:
            continue
        if prefix is not None and mod.__file__[:len(prefix)] != prefix:
            continue

        ## ignore if the .pyc is newer than the .py (or if there is no pyc or py)
        py = os.path.splitext(mod.__file__)[0] + '.py'
        pyc = py + 'c'
        if py not in changed and os.path.isfile(pyc) and os.path.isfile(py) and os.stat(pyc).st_mtime >= os.stat(py).st_mtime:
            #if debug:
                #print "Ignoring module %s; unchanged" % str(mod)
            continue
        changed.append(py)  ## keep track of which modules have changed to insure that duplicate-import modules get reloaded.

        try:
            reload(mod, debug=debug)
        except:
            printExc("Error while reloading module %s, skipping\n" % mod)
            failed.append(mod.__name__)

    if len(failed) > 0:
        raise Exception("Some modules failed to reload: %s" % ', '.join(failed))
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def reload(module, exclude=('sys', 'os.path', 'builtins', '__main__',
                            'numpy', 'numpy._globals')):
    """Recursively reload all modules used in the given module.  Optionally
    takes a list of modules to exclude from reloading.  The default exclude
    list contains sys, __main__, and __builtin__, to prevent, e.g., resetting
    display, exception, and io hooks.
    """
    global found_now
    for i in exclude:
        found_now[i] = 1
    try:
        with replace_import_hook(deep_import_hook):
            return deep_reload_hook(module)
    finally:
        found_now = {}
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
def reload(module, exclude=('sys', 'os.path', builtin_mod_name, '__main__',
                            'numpy', 'numpy._globals')):
    """Recursively reload all modules used in the given module.  Optionally
    takes a list of modules to exclude from reloading.  The default exclude
    list contains sys, __main__, and __builtin__, to prevent, e.g., resetting
    display, exception, and io hooks.
    """
    global found_now
    for i in exclude:
        found_now[i] = 1
    try:
        with replace_import_hook(deep_import_hook):
            return deep_reload_hook(module)
    finally:
        found_now = {}
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
def _dreload(module, **kwargs):
    """
    **deprecated**

    import reload explicitly from `IPython.lib.deepreload` to use it

    """
    # this was marked as deprecated and for 5.0 removal, but
    # IPython.core_builtin_trap have a Deprecation warning for 6.0, so cannot
    # remove that now.
    warn("""
injecting `dreload` in interactive namespace is deprecated since IPython 4.0. 
Please import `reload` explicitly from `IPython.lib.deepreload`.
""", DeprecationWarning, stacklevel=2)
    reload(module, **kwargs)
项目:blender    作者:gastrodia    | 项目源码 | 文件源码
def reload(module, exclude=('sys', 'os.path', builtin_mod_name, '__main__')):
    """Recursively reload all modules used in the given module.  Optionally
    takes a list of modules to exclude from reloading.  The default exclude
    list contains sys, __main__, and __builtin__, to prevent, e.g., resetting
    display, exception, and io hooks.
    """
    global found_now
    for i in exclude:
        found_now[i] = 1
    try:
        with replace_import_hook(deep_import_hook):
            return deep_reload_hook(module)
    finally:
        found_now = {}
项目:blender    作者:gastrodia    | 项目源码 | 文件源码
def _dreload(module, **kwargs):
    """
    **deprecated**

    import reload explicitly from `IPython.lib.deepreload` to use it

    """
    # this was marked as deprecated and for 5.0 removal, but
    # IPython.core_builtin_trap have a Deprecation warning for 6.0, so cannot
    # remove that now.
    warn("""
injecting `dreload` in interactive namespace is deprecated since IPython 4.0. 
Please import `reload` explicitly from `IPython.lib.deepreload`.
""", DeprecationWarning, stacklevel=2)
    reload(module, **kwargs)
项目:yatta_reader    作者:sound88    | 项目源码 | 文件源码
def reload(module, exclude=('sys', 'os.path', 'builtins', '__main__',
                            'numpy', 'numpy._globals')):
    """Recursively reload all modules used in the given module.  Optionally
    takes a list of modules to exclude from reloading.  The default exclude
    list contains sys, __main__, and __builtin__, to prevent, e.g., resetting
    display, exception, and io hooks.
    """
    global found_now
    for i in exclude:
        found_now[i] = 1
    try:
        with replace_import_hook(deep_import_hook):
            return deep_reload_hook(module)
    finally:
        found_now = {}
项目:coinbot    作者:pse1202    | 项目源码 | 文件源码
def run(self):
        while True:
            try:
                packet = self.msgQueue.get()
                if packet['type'] == 'msg':
                    msg = packet['content']
                    for channel in self.channel_list:
                        self.irc.sendmsg(channel, msg)

                elif packet['type'] == 'irc':
                    message = packet['content']
                    print(message)
                    if message.msgType == 'INVITE':
                        self.irc.joinchan(message.channel)

                    elif message.msgType == 'MODE':
                        if message.msg == '+o ' + self.irc.botnick:
                            self.irc.sendmsg(message.channel, '????? :)')

                    elif message.msgType == 'KICK':
                        pass

                    elif message.msgType == 'PRIVMSG':
                        val = functions.functionlist(message.msg)
                        if message.msg.find('!????') == 0:
                            reload(functions)
                            self.irc.sendmsg(message.channel, '???? ??')
                        elif val:
                            self.irc.sendmsg(message.channel, val)
                    elif message.msgType == 'NOTICE':
                        for chan in setting.chanlist:
                            self.irc.joinchan(chan)
            except Exception as err:
                with open('error.log','a') as f:
                    from datetime import datetime
                    f.write(str(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))+'\n' + str(traceback.format_exc()) + '\n')
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
def reload(module, debug=False, lists=False, dicts=False):
    """Replacement for the builtin reload function:
    - Reloads the module as usual
    - Updates all old functions and class methods to use the new code
    - Updates all instances of each modified class to use the new class
    - Can update lists and dicts, but this is disabled by default
    - Requires that class and function names have not changed
    """
    if debug:
        print("Reloading %s" % str(module))

    ## make a copy of the old module dictionary, reload, then grab the new module dictionary for comparison
    oldDict = module.__dict__.copy()
    builtins.reload(module)
    newDict = module.__dict__

    ## Allow modules access to the old dictionary after they reload
    if hasattr(module, '__reload__'):
        module.__reload__(oldDict)

    ## compare old and new elements from each dict; update where appropriate
    for k in oldDict:
        old = oldDict[k]
        new = newDict.get(k, None)
        if old is new or new is None:
            continue

        if inspect.isclass(old):
            if debug:
                print("  Updating class %s.%s (0x%x -> 0x%x)" % (module.__name__, k, id(old), id(new)))
            updateClass(old, new, debug)

        elif inspect.isfunction(old):
            depth = updateFunction(old, new, debug)
            if debug:
                extra = ""
                if depth > 0:
                    extra = " (and %d previous versions)" % depth
                print("  Updating function %s.%s%s" % (module.__name__, k, extra))
        elif lists and isinstance(old, list):
            l = old.len()
            old.extend(new)
            for i in range(l):
                old.pop(0)
        elif dicts and isinstance(old, dict):
            old.update(new)
            for k in old:
                if k not in new:
                    del old[k]



## For functions:
##  1) update the code and defaults to new versions.
##  2) keep a reference to the previous version so ALL versions get updated for every reload
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
def reload(module, debug=False, lists=False, dicts=False):
    """Replacement for the builtin reload function:
    - Reloads the module as usual
    - Updates all old functions and class methods to use the new code
    - Updates all instances of each modified class to use the new class
    - Can update lists and dicts, but this is disabled by default
    - Requires that class and function names have not changed
    """
    if debug:
        print("Reloading %s" % str(module))

    ## make a copy of the old module dictionary, reload, then grab the new module dictionary for comparison
    oldDict = module.__dict__.copy()
    builtins.reload(module)
    newDict = module.__dict__

    ## Allow modules access to the old dictionary after they reload
    if hasattr(module, '__reload__'):
        module.__reload__(oldDict)

    ## compare old and new elements from each dict; update where appropriate
    for k in oldDict:
        old = oldDict[k]
        new = newDict.get(k, None)
        if old is new or new is None:
            continue

        if inspect.isclass(old):
            if debug:
                print("  Updating class %s.%s (0x%x -> 0x%x)" % (module.__name__, k, id(old), id(new)))
            updateClass(old, new, debug)

        elif inspect.isfunction(old):
            depth = updateFunction(old, new, debug)
            if debug:
                extra = ""
                if depth > 0:
                    extra = " (and %d previous versions)" % depth
                print("  Updating function %s.%s%s" % (module.__name__, k, extra))
        elif lists and isinstance(old, list):
            l = old.len()
            old.extend(new)
            for i in range(l):
                old.pop(0)
        elif dicts and isinstance(old, dict):
            old.update(new)
            for k in old:
                if k not in new:
                    del old[k]



## For functions:
##  1) update the code and defaults to new versions.
##  2) keep a reference to the previous version so ALL versions get updated for every reload
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def deep_reload_hook(m):
    """Replacement for reload()."""
    # Hardcode this one  as it would raise a NotImplemeentedError from the
    # bowels of Python and screw up the import machinery after.
    # unlike other imports the `exclude` list aleady in place is not enough.

    if m is types:
        return m
    if not isinstance(m, ModuleType):
        raise TypeError("reload() argument must be module")

    name = m.__name__

    if name not in sys.modules:
        raise ImportError("reload(): module %.200s not in sys.modules" % name)

    global modules_reloading
    try:
        return modules_reloading[name]
    except:
        modules_reloading[name] = m

    dot = name.rfind('.')
    if dot < 0:
        subname = name
        path = None
    else:
        try:
            parent = sys.modules[name[:dot]]
        except KeyError:
            modules_reloading.clear()
            raise ImportError("reload(): parent %.200s not in sys.modules" % name[:dot])
        subname = name[dot+1:]
        path = getattr(parent, "__path__", None)

    try:
        # This appears to be necessary on Python 3, because imp.find_module()
        # tries to import standard libraries (like io) itself, and we don't
        # want them to be processed by our deep_import_hook.
        with replace_import_hook(original_import):
            fp, filename, stuff  = imp.find_module(subname, path)
    finally:
        modules_reloading.clear()

    try:
        newm = imp.load_module(name, fp, filename, stuff)
    except:
         # load_module probably removed name from modules because of
         # the error.  Put back the original module object.
        sys.modules[name] = m
        raise
    finally:
        if fp: fp.close()

    modules_reloading.clear()
    return newm

# Save the original hooks
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
def deep_reload_hook(m):
    """Replacement for reload()."""
    if not isinstance(m, ModuleType):
        raise TypeError("reload() argument must be module")

    name = m.__name__

    if name not in sys.modules:
        raise ImportError("reload(): module %.200s not in sys.modules" % name)

    global modules_reloading
    try:
        return modules_reloading[name]
    except:
        modules_reloading[name] = m

    dot = name.rfind('.')
    if dot < 0:
        subname = name
        path = None
    else:
        try:
            parent = sys.modules[name[:dot]]
        except KeyError:
            modules_reloading.clear()
            raise ImportError("reload(): parent %.200s not in sys.modules" % name[:dot])
        subname = name[dot+1:]
        path = getattr(parent, "__path__", None)

    try:
        # This appears to be necessary on Python 3, because imp.find_module()
        # tries to import standard libraries (like io) itself, and we don't
        # want them to be processed by our deep_import_hook.
        with replace_import_hook(original_import):
            fp, filename, stuff  = imp.find_module(subname, path)
    finally:
        modules_reloading.clear()

    try:
        newm = imp.load_module(name, fp, filename, stuff)
    except:
         # load_module probably removed name from modules because of
         # the error.  Put back the original module object.
        sys.modules[name] = m
        raise
    finally:
        if fp: fp.close()

    modules_reloading.clear()
    return newm

# Save the original hooks
项目:blender    作者:gastrodia    | 项目源码 | 文件源码
def deep_reload_hook(m):
    """Replacement for reload()."""
    if not isinstance(m, ModuleType):
        raise TypeError("reload() argument must be module")

    name = m.__name__

    if name not in sys.modules:
        raise ImportError("reload(): module %.200s not in sys.modules" % name)

    global modules_reloading
    try:
        return modules_reloading[name]
    except:
        modules_reloading[name] = m

    dot = name.rfind('.')
    if dot < 0:
        subname = name
        path = None
    else:
        try:
            parent = sys.modules[name[:dot]]
        except KeyError:
            modules_reloading.clear()
            raise ImportError("reload(): parent %.200s not in sys.modules" % name[:dot])
        subname = name[dot+1:]
        path = getattr(parent, "__path__", None)

    try:
        # This appears to be necessary on Python 3, because imp.find_module()
        # tries to import standard libraries (like io) itself, and we don't
        # want them to be processed by our deep_import_hook.
        with replace_import_hook(original_import):
            fp, filename, stuff  = imp.find_module(subname, path)
    finally:
        modules_reloading.clear()

    try:
        newm = imp.load_module(name, fp, filename, stuff)
    except:
         # load_module probably removed name from modules because of
         # the error.  Put back the original module object.
        sys.modules[name] = m
        raise
    finally:
        if fp: fp.close()

    modules_reloading.clear()
    return newm

# Save the original hooks
项目:yatta_reader    作者:sound88    | 项目源码 | 文件源码
def deep_reload_hook(m):
    """Replacement for reload()."""
    # Hardcode this one  as it would raise a NotImplemeentedError from the
    # bowels of Python and screw up the import machinery after.
    # unlike other imports the `exclude` list aleady in place is not enough.

    if m is types:
        return m
    if not isinstance(m, ModuleType):
        raise TypeError("reload() argument must be module")

    name = m.__name__

    if name not in sys.modules:
        raise ImportError("reload(): module %.200s not in sys.modules" % name)

    global modules_reloading
    try:
        return modules_reloading[name]
    except:
        modules_reloading[name] = m

    dot = name.rfind('.')
    if dot < 0:
        subname = name
        path = None
    else:
        try:
            parent = sys.modules[name[:dot]]
        except KeyError:
            modules_reloading.clear()
            raise ImportError("reload(): parent %.200s not in sys.modules" % name[:dot])
        subname = name[dot+1:]
        path = getattr(parent, "__path__", None)

    try:
        # This appears to be necessary on Python 3, because imp.find_module()
        # tries to import standard libraries (like io) itself, and we don't
        # want them to be processed by our deep_import_hook.
        with replace_import_hook(original_import):
            fp, filename, stuff  = imp.find_module(subname, path)
    finally:
        modules_reloading.clear()

    try:
        newm = imp.load_module(name, fp, filename, stuff)
    except:
         # load_module probably removed name from modules because of
         # the error.  Put back the original module object.
        sys.modules[name] = m
        raise
    finally:
        if fp: fp.close()

    modules_reloading.clear()
    return newm

# Save the original hooks