pkg_resources module

Package resource API

A resource is a logical file contained within a package, or a logical subdirectory thereof. The package resource API expects resource names to have their path parts separated with /, not whatever the local path separator is. Do not use os.path operations to manipulate resource names being passed into the API.

The package resource API is designed to work with normal filesystem packages, .egg files, and unpacked .egg files. It can also work in a limited way with .zip files and with custom PEP 302 loaders that support the get_data() method.


Return an IResourceProvider for the named module or requirement


Return a current distribution object for a Requirement or string

pkg_resources.load_entry_point(dist, group, name)[source]

Return name entry point of group for dist or raise ImportError

pkg_resources.get_entry_map(dist, group=None)[source]

Return the entry point map for group, or the full entry map

pkg_resources.get_entry_info(dist, group, name)[source]

Return the EntryPoint object for group`+`name, or None


Declare that package ‘packageName’ is a namespace package

pkg_resources.find_distributions(path_item, only=False)[source]

Yield distributions accessible via path_item


Determine the default cache location

This returns the PYTHON_EGG_CACHE environment variable, if set. Otherwise, on Windows, it returns a “Python-Eggs” subdirectory of the “Application Data” directory. On all other systems, it’s “~/.python-eggs”.

class pkg_resources.Environment(search_path=None, platform='linux-x86_64', python='2.7')[source]

Bases: object

Searchable snapshot of distributions on a search path


Add dist if we can_add() it and it has not already been added

best_match(req, working_set, installer=None)[source]

Find distribution best matching req and usable on working_set

This calls the find(req) method of the working_set to see if a suitable distribution is already active. (This may raise VersionConflict if an unsuitable version of the project is already active in the specified working_set.) If a suitable distribution isn’t active, this method returns the newest distribution in the environment that meets the Requirement in req. If no suitable distribution is found, and installer is supplied, then the result of calling the environment’s obtain(req, installer) method will be returned.


Is distribution dist acceptable for this environment?

The distribution must match the platform and python version requirements specified when this environment was created, or False is returned.

obtain(requirement, installer=None)[source]

Obtain a distribution matching requirement (e.g. via download)

Obtain a distro that matches requirement (e.g. via download). In the base Environment class, this routine just returns installer(requirement), unless installer is None, in which case None is returned instead. This method is a hook that allows subclasses to attempt other ways of obtaining a distribution before falling back to the installer argument.


Remove dist from the environment


Scan search_path for distributions usable in this environment

Any distributions found are added to the environment. search_path should be a sequence of sys.path items. If not supplied, sys.path is used. Only distributions conforming to the platform/python version defined at initialization are added.

class pkg_resources.WorkingSet(entries=None)[source]

Bases: object

A collection of active distributions on sys.path (or a similar list)

add(dist, entry=None, insert=True, replace=False)[source]

Add dist to working set, associated with entry

If entry is unspecified, it defaults to the .location of dist. On exit from this routine, entry is added to the end of the working set’s .entries (if it wasn’t already present).

dist is only added to the working set if it’s for a project that doesn’t already have a distribution in the set, unless replace=True. If it’s added, any callbacks registered with the subscribe() method will be called.


Add a path item to .entries, finding any distributions on it

find_distributions(entry, True) is used to find distributions corresponding to the path entry, and they are added. entry is always appended to .entries, even if it is already present. (This is because sys.path can contain the same value more than once, and the .entries of the sys.path WorkingSet should always equal sys.path.)


Find a distribution matching requirement req

If there is an active distribution for the requested project, this returns it as long as it meets the version requirement specified by req. But, if there is an active distribution for the project and it does not meet the req requirement, VersionConflict is raised. If there is no active distribution for the requested project, None is returned.

find_plugins(plugin_env, full_env=None, installer=None, fallback=True)[source]

Find all activatable distributions in plugin_env

Example usage:

distributions, errors = working_set.find_plugins(
# add plugins+libs to sys.path
map(working_set.add, distributions)
# display errors
print('Could not load', errors)

The plugin_env should be an Environment instance that contains only distributions that are in the project’s “plugin directory” or directories. The full_env, if supplied, should be an Environment contains all currently-available distributions. If full_env is not supplied, one is created automatically from the WorkingSet this method is called on, which will typically mean that every directory on sys.path will be scanned for distributions.

installer is a standard installer callback as used by the resolve() method. The fallback flag indicates whether we should attempt to resolve older versions of a plugin if the newest version cannot be resolved.

This method returns a 2-tuple: (distributions, error_info), where distributions is a list of the distributions found in plugin_env that were loadable, along with any other distributions that are needed to resolve their dependencies. error_info is a dictionary mapping unloadable plugin distributions to an exception instance describing the error that occurred. Usually this will be a DistributionNotFound or VersionConflict instance.

iter_entry_points(group, name=None)[source]

Yield entry point objects from group matching name

If name is None, yields all entry points in group from all distributions in the working set, otherwise only ones matching both group and name are yielded (in distribution order).


Ensure that distributions matching requirements are activated

requirements must be a string or a (possibly-nested) sequence thereof, specifying the distributions and versions required. The return value is a sequence of the distributions that needed to be activated to fulfill the requirements; all relevant distributions are included, even if they were already activated in this working set.

resolve(requirements, env=None, installer=None, replace_conflicting=False)[source]

List all distributions needed to (recursively) meet requirements

requirements must be a sequence of Requirement objects. env, if supplied, should be an Environment instance. If not supplied, it defaults to all distributions available within any entry or distribution in the working set. installer, if supplied, will be invoked with each requirement that cannot be met by an already-installed distribution; it should return a Distribution or None.

Unless replace_conflicting=True, raises a VersionConflict exception if any requirements are found on the path that have the correct name but the wrong version. Otherwise, if an installer is supplied it will be invoked to obtain the correct version of the requirement and activate it.

run_script(requires, script_name)[source]

Locate distribution for requires and run script_name script


Invoke callback for all distributions (including existing ones)

class pkg_resources.ResourceManager[source]

Manage resource extraction and packages


Delete all extracted resource files and directories, returning a list of the file and directory names that could not be successfully removed. This function does not have any concurrency protection, so it should generally only be called when the extraction path is a temporary directory exclusive to a single process. This method is not automatically called; you must call it explicitly or register it as an atexit function if you wish to ensure cleanup of a temporary directory used for extractions.


Give an error message for problems extracting file(s)

extraction_path = None
get_cache_path(archive_name, names=())[source]

Return absolute location in cache for archive_name and names

The parent directory of the resulting path will be created if it does not already exist. archive_name should be the base filename of the enclosing egg (which may not be the name of the enclosing zipfile!), including its ”.egg” extension. names, if provided, should be a sequence of path name parts “under” the egg’s extraction location.

This method should only be called by resource providers that need to obtain an extraction location, and only for names they intend to extract, as it tracks the generated names for possible cleanup later.

postprocess(tempname, filename)[source]

Perform any platform-specific postprocessing of tempname

This is where Mac header rewrites should be done; other platforms don’t have anything special they should do.

Resource providers should call this method ONLY after successfully extracting a compressed resource. They must NOT call it on resources that are already in the filesystem.

tempname is the current (temporary) name of the file, and filename is the name it will be renamed to by the caller after this routine returns.

resource_exists(package_or_requirement, resource_name)[source]

Does the named resource exist?

resource_filename(package_or_requirement, resource_name)[source]

Return a true filesystem path for specified resource

resource_isdir(package_or_requirement, resource_name)[source]

Is the named resource an existing directory?

resource_listdir(package_or_requirement, resource_name)[source]

List the contents of the named resource directory

resource_stream(package_or_requirement, resource_name)[source]

Return a readable file-like object for specified resource

resource_string(package_or_requirement, resource_name)[source]

Return specified resource as a string


Set the base path where resources will be extracted to, if needed.

If you do not call this routine before any extractions take place, the path defaults to the return value of get_default_cache(). (Which is based on the PYTHON_EGG_CACHE environment variable, with various platform-specific fallbacks. See that routine’s documentation for more details.)

Resources are extracted to subdirectories of this path based upon information given by the IResourceProvider. You may set this to a temporary directory, but then you must call cleanup_resources() to delete the extracted files when done. There is no guarantee that cleanup_resources() will be able to remove all extracted files.

(Note: you may not change the extraction path for a given resource manager once resources have been extracted, unless you first call cleanup_resources().)

class pkg_resources.Distribution(location=None, metadata=None, project_name=None, version=None, py_version='2.7', platform=None, precedence=3)[source]

Bases: object

Wrap an actual or potential sys.path entry w/metadata


Ensure distribution is importable on path (default=sys.path)


Return a Requirement that matches this distribution exactly


Copy this distribution, substituting in any changed keyword args


Return what this distribution’s standard .egg filename should be

classmethod from_filename(filename, metadata=None, **kw)[source]
classmethod from_location(location, basename, metadata=None, **kw)[source]
get_entry_info(group, name)[source]

Return the EntryPoint object for group`+`name, or None


Return the entry point map for group, or the full entry map

insert_on(path, loc=None)

Insert self.location in path before its nearest parent directory

load_entry_point(group, name)[source]

Return the name entry point of group or raise ImportError


List of Requirements needed for this distro if extras are used

class pkg_resources.Requirement(project_name, specs, extras)[source]
static parse(s)[source]
class pkg_resources.EntryPoint(name, module_name, attrs=(), extras=(), dist=None)[source]

Bases: object

Object representing an advertised importable object

load(require=True, *args, **kwargs)[source]

Require packages for this EntryPoint, then resolve it.

classmethod parse(src, dist=None)[source]

Parse a single entry point from string src

Entry point syntax follows the form:

name = some.module:some.attr [extra1, extra2]

The entry name and module name are required, but the :attrs and [extras] parts are optional

classmethod parse_group(group, lines, dist=None)[source]

Parse an entry point group

classmethod parse_map(data, dist=None)[source]

Parse a map of entry point groups

pattern = <_sre.SRE_Pattern object at 0x20153f0>
require(env=None, installer=None)[source]

Resolve the entry point from its module and attrs.

exception pkg_resources.ResolutionError[source]

Bases: exceptions.Exception

Abstract base for dependency resolution errors

exception pkg_resources.VersionConflict[source]

Bases: pkg_resources.ResolutionError

An already-installed version conflicts with the requested version.

Should be initialized with the installed Distribution and the requested Requirement.


If required_by is non-empty, return a version of self that is a ContextualVersionConflict.

exception pkg_resources.DistributionNotFound[source]

Bases: pkg_resources.ResolutionError

A requested distribution was not found

exception pkg_resources.UnknownExtra[source]

Bases: pkg_resources.ResolutionError

Distribution doesn’t have an “extra feature” of the given name

exception pkg_resources.ExtractionError[source]

Bases: exceptions.RuntimeError

An error occurred extracting a resource

The following attributes are available from instances of this exception:

The resource manager that raised this exception
The base directory for resource extraction
The exception instance that caused extraction to fail
exception pkg_resources.PEP440Warning[source]

Bases: exceptions.RuntimeWarning

Used when there is an issue with a version or specifier not complying with PEP 440.


Yield Requirement objects for each specification in strs

strs must be a string, or a (possibly-nested) iterable thereof.


Convert an arbitrary string to a standard distribution name

Any runs of non-alphanumeric/. characters are replaced with a single ‘-‘.


Convert an arbitrary string to a standard version string

pkg_resources.compatible_platforms(provided, required)[source]

Can code for the provided platform run on the required platform?

Returns true if either platform is None, or the platforms are equal.

XXX Needs compatibility checks for Linux and other unixy OSes.


Yield non-empty/non-comment lines of a string or sequence


Split a string or iterable thereof into (section, content) pairs

Each section is a stripped version of the section header (“[section]”) and each content is a list of stripped lines excluding blank lines and comment-only lines. If there are any such lines before the first section header, they’re returned in a first section of None.


Convert an arbitrary string to a standard ‘extra’ name

Any runs of non-alphanumeric characters are replaced with a single ‘_’, and the result is always lowercased.


Convert a project or version name to its filename-escaped form

Any ‘-‘ characters are currently replaced with ‘_’.


Ensure that the parent directory of path exists


Normalize a file/dir name for comparison purposes

class pkg_resources.IMetadataProvider[source]

The named metadata resource as a string


Yield named metadata resource as list of non-blank non-comment lines

Leading and trailing whitespace is stripped from each line, and lines with # as the first non-blank character are omitted.


Does the package’s distribution contain the named metadata?


Is the named metadata a directory? (like os.path.isdir())


List of metadata names in the directory (like os.listdir())

run_script(script_name, namespace)[source]

Execute the named script in the supplied namespace dictionary

class pkg_resources.IResourceProvider[source]

Bases: pkg_resources.IMetadataProvider

An object that provides access to package resources

get_resource_filename(manager, resource_name)[source]

Return a true filesystem path for resource_name

manager must be an IResourceManager

get_resource_stream(manager, resource_name)[source]

Return a readable file-like object for resource_name

manager must be an IResourceManager

get_resource_string(manager, resource_name)[source]

Return a string containing the contents of resource_name

manager must be an IResourceManager


Does the package contain the named resource?


Is the named resource a directory? (like os.path.isdir())


List of resource names in the directory (like os.listdir())

class pkg_resources.FileMetadata(path)[source]

Bases: pkg_resources.EmptyProvider

Metadata handler for standalone PKG-INFO files


metadata = FileMetadata("/path/to/PKG-INFO")

This provider rejects all data and metadata requests except for PKG-INFO, which is treated as existing, and will be the contents of the file at the provided location.

class pkg_resources.PathMetadata(path, egg_info)[source]

Bases: pkg_resources.DefaultProvider

Metadata provider for egg directories


# Development eggs:

egg_info = "/path/to/PackageName.egg-info"
base_dir = os.path.dirname(egg_info)
metadata = PathMetadata(base_dir, egg_info)
dist_name = os.path.splitext(os.path.basename(egg_info))[0]
dist = Distribution(basedir, project_name=dist_name, metadata=metadata)

# Unpacked egg directories:

egg_path = "/path/to/PackageName-ver-pyver-etc.egg"
metadata = PathMetadata(egg_path, os.path.join(egg_path,'EGG-INFO'))
dist = Distribution.from_filename(egg_path, metadata=metadata)
class pkg_resources.EggMetadata(importer)[source]

Bases: pkg_resources.ZipProvider

Metadata provider for .egg files

class pkg_resources.EmptyProvider[source]

Bases: pkg_resources.NullProvider

Provider that returns nothing for all requests

module_path = None
class pkg_resources.NullProvider(module)[source]

Try to implement resources and metadata for arbitrary PEP 302 loaders

egg_info = None
egg_name = None
get_resource_filename(manager, resource_name)[source]
get_resource_stream(manager, resource_name)[source]
get_resource_string(manager, resource_name)[source]
loader = None
run_script(script_name, namespace)[source]
class pkg_resources.EggProvider(module)[source]

Bases: pkg_resources.NullProvider

Provider based on a virtual filesystem

class pkg_resources.DefaultProvider(module)[source]

Bases: pkg_resources.EggProvider

Provides access to package resources in the filesystem

get_resource_stream(manager, resource_name)[source]
class pkg_resources.ZipProvider(module)[source]

Bases: pkg_resources.EggProvider

Resource support for zips and eggs

eagers = None
get_resource_filename(manager, resource_name)[source]
pkg_resources.register_finder(importer_type, distribution_finder)[source]

Register distribution_finder to find distributions in sys.path items

importer_type is the type or class of a PEP 302 “Importer” (sys.path item handler), and distribution_finder is a callable that, passed a path item and the importer instance, yields Distribution instances found on that path item. See pkg_resources.find_on_path for an example.

pkg_resources.register_namespace_handler(importer_type, namespace_handler)[source]

Register namespace_handler to declare namespace packages

importer_type is the type or class of a PEP 302 “Importer” (sys.path item handler), and namespace_handler is a callable like this:

def namespace_handler(importer, path_entry, moduleName, module):
    # return a path_entry to use for child packages

Namespace handlers are only called if the importer object has already agreed that it can handle the relevant path item, and they should only return a subpath if the module __path__ does not already contain an equivalent subpath. For an example namespace handler, see pkg_resources.file_ns_handler.

pkg_resources.register_loader_type(loader_type, provider_factory)[source]

Register provider_factory to make providers for loader_type

loader_type is the type or class of a PEP 302 module.__loader__, and provider_factory is a function that, passed a module object, returns an IResourceProvider for that module.

pkg_resources.fixup_namespace_packages(path_item, parent=None)[source]

Ensure that previously-declared namespace packages include path_item


Retrieve a PEP 302 importer for the given path item

The returned importer is cached in sys.path_importer_cache if it was newly created by a path hook.

If there is no importer, a wrapper around the basic import machinery is returned. This wrapper is never inserted into the importer cache (None is inserted instead).

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


alias of Environment