• pkgutil —- Package extension utility

    pkgutil —- Package extension utility

    Source code:Lib/pkgutil.py


    This module provides utilities for the import system, in particular packagesupport.

    • class pkgutil.ModuleInfo(module_finder, name, ispkg)
    • A namedtuple that holds a brief summary of a module's info.

    3.6 新版功能.

    • pkgutil.extendpath(_path, name)
    • Extend the search path for the modules which comprise a package. Intendeduse is to place the following code in a package's init.py:
    1. from pkgutil import extend_path
    2. __path__ = extend_path(__path__, __name__)

    This will add to the package's path all subdirectories of directorieson sys.path named after the package. This is useful if one wants todistribute different parts of a single logical package as multipledirectories.

    It also looks for .pkg files beginning where matches thename argument. This feature is similar to .pth files (see thesite module for more information), except that it doesn't special-caselines starting with import. A .pkg file is trusted at facevalue: apart from checking for duplicates, all entries found in a*.pkg file are added to the path, regardless of whether they existon the filesystem. (This is a feature.)

    If the input path is not a list (as is the case for frozen packages) it isreturned unchanged. The input path is not modified; an extended copy isreturned. Items are only appended to the copy at the end.

    It is assumed that sys.path is a sequence. Items of sys.paththat are not strings referring to existing directories are ignored. Unicodeitems on sys.path that cause errors when used as filenames may causethis function to raise an exception (in line with os.path.isdir()behavior).

    • class pkgutil.ImpImporter(dirname=None)
    • PEP 302 Finder that wraps Python's "classic" import algorithm.

    If dirname is a string, a PEP 302 finder is created that searches thatdirectory. If dirname is None, a PEP 302 finder is created thatsearches the current sys.path, plus any modules that are frozen orbuilt-in.

    Note that ImpImporter does not currently support being used byplacement on sys.meta_path.

    3.3 版后已移除: This emulation is no longer needed, as the standard import mechanismis now fully PEP 302 compliant and available in importlib.

    • class pkgutil.ImpLoader(fullname, file, filename, etc)
    • Loader that wraps Python's "classic" import algorithm.

    3.3 版后已移除: This emulation is no longer needed, as the standard import mechanismis now fully PEP 302 compliant and available in importlib.

    • pkgutil.findloader(_fullname)
    • Retrieve a module loader for the given fullname.

    This is a backwards compatibility wrapper aroundimportlib.util.find_spec() that converts most failures toImportError and only returns the loader rather than the fullModuleSpec.

    在 3.3 版更改: Updated to be based directly on importlib rather than relyingon the package internal PEP 302 import emulation.

    在 3.4 版更改: Updated to be based on PEP 451

    • pkgutil.getimporter(_path_item)
    • Retrieve a finder for the given path_item.

    The returned finder is cached in sys.path_importer_cache if it wasnewly created by a path hook.

    The cache (or part of it) can be cleared manually if a rescan ofsys.path_hooks is necessary.

    在 3.3 版更改: Updated to be based directly on importlib rather than relyingon the package internal PEP 302 import emulation.

    • pkgutil.getloader(_module_or_name)
    • Get a loader object for module_or_name.

    If the module or package is accessible via the normal import mechanism, awrapper around the relevant part of that machinery is returned. ReturnsNone if the module cannot be found or imported. If the named module isnot already imported, its containing package (if any) is imported, in orderto establish the package path.

    在 3.3 版更改: Updated to be based directly on importlib rather than relyingon the package internal PEP 302 import emulation.

    在 3.4 版更改: Updated to be based on PEP 451

    • pkgutil.iterimporters(_fullname='')
    • Yield finder objects for the given module name.

    If fullname contains a '.', the finders will be for the packagecontaining fullname, otherwise they will be all registered top levelfinders (i.e. those on both sys.meta_path and sys.path_hooks).

    If the named module is in a package, that package is imported as a sideeffect of invoking this function.

    If no module name is specified, all top level finders are produced.

    在 3.3 版更改: Updated to be based directly on importlib rather than relyingon the package internal PEP 302 import emulation.

    • pkgutil.itermodules(_path=None, prefix='')
    • Yields ModuleInfo for all submodules on path, or, ifpath is None, all top-level modules on sys.path.

    path should be either None or a list of paths to look for modules in.

    prefix is a string to output on the front of every module name on output.

    注解

    Only works for a finder which defines an iter_modules()method. This interface is non-standard, so the module also providesimplementations for importlib.machinery.FileFinder andzipimport.zipimporter.

    在 3.3 版更改: Updated to be based directly on importlib rather than relyingon the package internal PEP 302 import emulation.

    • pkgutil.walkpackages(_path=None, prefix='', onerror=None)
    • Yields ModuleInfo for all modules recursively onpath, or, if path is None, all accessible modules.

    path should be either None or a list of paths to look for modules in.

    prefix is a string to output on the front of every module name on output.

    Note that this function must import all packages (not all modules!) onthe given path, in order to access the path attribute to findsubmodules.

    onerror is a function which gets called with one argument (the name of thepackage which was being imported) if any exception occurs while trying toimport a package. If no onerror function is supplied, ImportErrorsare caught and ignored, while all other exceptions are propagated,terminating the search.

    例如:

    1. # list all modules python can access
    2. walk_packages()
    3.  
    4. # list all submodules of ctypes
    5. walk_packages(ctypes.__path__, ctypes.__name__ + '.')

    注解

    Only works for a finder which defines an iter_modules()method. This interface is non-standard, so the module also providesimplementations for importlib.machinery.FileFinder andzipimport.zipimporter.

    在 3.3 版更改: Updated to be based directly on importlib rather than relyingon the package internal PEP 302 import emulation.

    • pkgutil.getdata(_package, resource)
    • Get a resource from a package.

    This is a wrapper for the loaderget_data API. Thepackage argument should be the name of a package, in standard module format(foo.bar). The resource argument should be in the form of a relativefilename, using / as the path separator. The parent directory name.. is not allowed, and nor is a rooted name (starting with a /).

    The function returns a binary string that is the contents of the specifiedresource.

    For packages located in the filesystem, which have already been imported,this is the rough equivalent of:

    1. d = os.path.dirname(sys.modules[package].__file__)
    2. data = open(os.path.join(d, resource), 'rb').read()

    If the package cannot be located or loaded, or it uses a loaderwhich does not support get_data,then None is returned. In particular, the loader fornamespace packages does not supportget_data.