通过path获取module

from importlib import import_module
def load_object(path):
    """Load an object given its absolute object path, and return it.

    object can be a class, function, variable or an instance.
    path ie: 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware'
    """

    try:
        dot = path.rindex('.')
    except ValueError:
        raise ValueError("Error loading object '%s': not a full path" % path)

    module, name = path[:dot], path[dot+1:]
    # module, _, name = path.rpartition(".")
    # if not all([module,name]):raise ValueError("Error loading object '%s': not a full path" % path)
    mod = import_module(module)


    try:
        obj = getattr(mod, name)
    except AttributeError:
        raise NameError("Module '%s' doesn't define any object named '%s'" % (module, name))

    return obj
通过path获取module。在多处有使用,如scrapy/django的中间件导入

相关文章: