饭叔的知识整理

python 关于imp

The imp module includes functions that expose part of the underlying implementation of Python’s import mechanism for loading code in packages and modules. It is one access point to importing modules dynamically, and useful in some cases where you don’t know the name of the module you need to import when you write your code (e.g., for plugins or extensions to an application).

Problem

You have code in either compiled or source form and need to wrap it in a module, possibly adding it to sys.modules as well.

Solution

We build a new module object, optionally add it to sys.modules, and populate it with an exec statement:

def importCode(code, name, add_to_sys_modules=0):
    """ code can be any object containing code -- string, file object, or
       compiled code object. Returns a new module object initialized
       by dynamically importing the given code and optionally adds it
       to sys.modules under the given name.
    """
    import imp
    module = imp.new_module(name)

    if add_to_sys_modules:
        import sys
        sys.modules[name] = module
    exec code in module._ _dict_ _

    return module

参考:

https://pymotw.com/2/imp/
https://docs.python.org/2/library/imp.html