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.
New in version 3.6.
pkgutil.extend_path(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:frompkgutilimportextend_path__path__=extend_path(__path__,__name__)
This will add to the package’s
__path__all subdirectories of directoriesonsys.pathnamed after the package. This is useful if one wants todistribute different parts of a single logical package as multipledirectories.It also looks for
*.pkgfiles beginning where*matches thename argument. This feature is similar to*.pthfiles (see thesitemodule for more information), except that it doesn’t special-caselines starting withimport. A*.pkgfile is trusted at facevalue: apart from checking for duplicates, all entries found in a*.pkgfile 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.pathis a sequence. Items ofsys.paththat are not strings referring to existing directories are ignored. Unicodeitems onsys.paththat cause errors when used as filenames may causethis function to raise an exception (in line withos.path.isdir()behavior).
- class
pkgutil.ImpImporter(dirname=None)¶ PEP 302 Finder that wraps Python’s “classic” import algorithm.
Ifdirname is a string, aPEP 302 finder is created that searches thatdirectory. Ifdirname is
None, aPEP 302 finder is created thatsearches the currentsys.path, plus any modules that are frozen orbuilt-in.Note that
ImpImporterdoes not currently support being used byplacement onsys.meta_path.
- class
pkgutil.ImpLoader(fullname,file,filename,etc)¶ Loader that wraps Python’s “classic” import algorithm.
pkgutil.find_loader(fullname)¶Retrieve a moduleloader for the givenfullname.
This is a backwards compatibility wrapper around
importlib.util.find_spec()that converts most failures toImportErrorand only returns the loader rather than the fullModuleSpec.Changed in version 3.3:Updated to be based directly on
importlibrather than relyingon the package internalPEP 302 import emulation.Changed in version 3.4:Updated to be based onPEP 451
pkgutil.get_importer(path_item)¶Retrieve afinder for the givenpath_item.
The returned finder is cached in
sys.path_importer_cacheif it wasnewly created by a path hook.The cache (or part of it) can be cleared manually if a rescan of
sys.path_hooksis necessary.
pkgutil.get_loader(module_or_name)¶Get aloader object formodule_or_name.
If the module or package is accessible via the normal import mechanism, awrapper around the relevant part of that machinery is returned. Returns
Noneif 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__.Changed in version 3.3:Updated to be based directly on
importlibrather than relyingon the package internalPEP 302 import emulation.Changed in version 3.4:Updated to be based onPEP 451
pkgutil.iter_importers(fullname='')¶Yieldfinder 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.
pkgutil.iter_modules(path=None,prefix='')¶Yields
ModuleInfofor all submodules onpath, or, ifpath isNone, all top-level modules onsys.path.path should be either
Noneor 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
Only works for afinder which defines an
iter_modules()method. This interface is non-standard, so the module also providesimplementations forimportlib.machinery.FileFinderandzipimport.zipimporter.
pkgutil.walk_packages(path=None,prefix='',onerror=None)¶Yields
ModuleInfofor all modules recursively onpath, or, ifpath isNone, all accessible modules.path should be either
Noneor 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 allpackages (not all modules!) onthe givenpath, 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 noonerror function is supplied,
ImportErrorsare caught and ignored, while all other exceptions are propagated,terminating the search.Examples:
# list all modules python can accesswalk_packages()# list all submodules of ctypeswalk_packages(ctypes.__path__,ctypes.__name__+'.')
Note
Only works for afinder which defines an
iter_modules()method. This interface is non-standard, so the module also providesimplementations forimportlib.machinery.FileFinderandzipimport.zipimporter.
pkgutil.get_data(package,resource)¶Get a resource from a package.
This is a wrapper for theloader
get_dataAPI. Thepackage argument should be the name of a package, in standard module format(foo.bar). Theresource 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:
d=os.path.dirname(sys.modules[package].__file__)data=open(os.path.join(d,resource),'rb').read()
If the package cannot be located or loaded, or it uses aloaderwhich does not support
get_data,thenNoneis returned. In particular, theloader fornamespace packages does not supportget_data.