archive-com.com » COM » T » TELECOMMUNITY.COM

Total: 388

Choose link from "Titles, links and description words view":

Or switch to "Titles and links view".
  • Diff for "PkgResources" - The PEAK Developers' Center
    whitespace Differences between version dated 2010 01 30 16 10 06 and 2010 01 31 00 36 31 Deletions are marked like this Additions are marked like this distribution A file or files that represent a particular release importable distribution importable distribution A file or directory that if placed on sys path allows Python to import any modules contained within it ShowText of this page EditText of this page FindPage

    Original URL path: http://peak.telecommunity.com/DevCenter/PkgResources?action=diff (2016-04-24)
    Open archived version from archive


  • Info for "PkgResources" - The PEAK Developers' Center
    version view diff 7 2008 09 19 12 10 28 94546 static 63 131 36 30 man onecommunications net view diff 8 2008 02 15 13 10 20 94540 Phillip J Eby view diff 9 2007 09 04 12 50 24 94539 Phillip J Eby 0 6c7 release view diff 10 2007 08 11 11 33 05 94340 Phillip J Eby Revert spam view diff 11 2007 08 11 07 08 53 96827 203 89 185 88 view diff 12 2007 05 31 13 56 12 94341 Phillip J Eby Updated to version 0 6c6 view diff 13 2006 09 20 17 13 17 93899 Phillip J Eby 0 6c3 Support Python 2 5 and svn 1 4 view diff 14 2006 09 06 17 10 16 93640 Phillip J Eby 0 6c2 bug fixes view diff 15 2006 07 11 14 52 24 93422 Phillip J Eby 0 6b4 documentation changes only view diff 16 2006 06 09 14 36 33 92249 Phillip J Eby view diff 17 2006 05 12 18 49 27 91701 Phillip J Eby 0 6b1 minor bug fixes view diff 18 2006 03 29 18 53 51 90755 Phillip J Eby 0 6a11 add ExtractionError minor bugfixes view diff 19 2006 02 14 16 14 50 89645 Phillip J Eby 0 6a10 misc enhancements to support easy install features view diff 20 2006 01 04 13 23 06 82716 Phillip J Eby 0 6a9 robustness improvements view diff 21 2005 11 22 20 03 01 81091 Phillip J Eby Document how to hook in an auto install facility view diff 22 2005 11 22 18 22 32 80739 207 118 85 171 dyn centurytel net Clarify that require doesn t install missing packages view diff 23 2005 11 16 16 50 41 80448 Phillip

    Original URL path: http://peak.telecommunity.com/DevCenter/PkgResources?action=info (2016-04-24)
    Open archived version from archive

  • PkgResources - The PEAK Developers' Center
    a shortcut for using the find distributions function to find the distributions from each item in search path and then calling add to add each one to the environment Requirement Objects Requirement objects express what versions of a project are suitable for some purpose These objects or their string form are used by various pkg resources APIs in order to find distributions that a script or distribution needs Requirements Parsing parse requirements s Yield Requirement objects for a string or iterable of lines Each requirement must start on a new line See below for syntax Requirement parse s Create a Requirement object from a string or iterable of lines A ValueError is raised if the string or lines do not contain a valid requirement specifier or if they contain more than one specifier To parse multiple specifiers from a string or iterable of strings use parse requirements instead The syntax of a requirement specifier can be defined in EBNF as follows requirement project name versionspec extras versionspec comparison version comparison version comparison extras extralist extralist identifier identifier project name identifier identifier A Za z0 9 version A Za z0 9 Tokens can be separated by whitespace and a requirement can be continued over multiple lines using a backslash Line end comments using are also allowed Some examples of valid requirement specifiers FooProject 1 2 Fizzy foo bar PickyThing 1 6 1 9 1 9 6 2 0a0 2 4c1 SomethingWhoseVersionIDontCareAbout The project name is the only required portion of a requirement string and if it s the only thing supplied the requirement will accept any version of that project The extras in a requirement are used to request optional features of a project that may require additional project distributions in order to function For example if the hypothetical Report O Rama project offered optional PDF support it might require an additional library in order to provide that support Thus a project needing Report O Rama s PDF features could use a requirement of Report O Rama PDF to request installation or activation of both Report O Rama and any libraries it needs in order to provide PDF support For example you could use easy install py Report O Rama PDF To install the necessary packages using the EasyInstall program or call pkg resources require Report O Rama PDF to add the necessary distributions to sys path at runtime Requirement Methods and Attributes contains dist or version Return true if dist or version fits the criteria for this requirement If dist or version is a Distribution object its project name must match the requirement s project name and its version must meet the requirement s version criteria If dist or version is a string it is parsed using the parse version utility function Otherwise it is assumed to be an already parsed version The Requirement object s version specifiers specs are internally sorted into ascending version order and used to establish what ranges of versions are acceptable Adjacent redundant conditions are effectively consolidated e g 1 2 produces the same results as 1 and 2 3 produces the same results as 3 versions are excised from the ranges they fall within The version being tested for acceptability is then checked for membership in the resulting ranges Note that providing conflicting conditions for the same version e g 2 2 or 2 2 is meaningless and may therefore produce bizarre results when compared with actual version number s eq other requirement A requirement compares equal to another requirement if they have case insensitively equal project names version specifiers and extras The order that extras and version specifiers are in is also ignored Equal requirements also have equal hashes so that requirements can be used in sets or as dictionary keys str The string form of a Requirement is a string that if passed to Requirement parse would return an equal Requirement object project name The name of the required project key An all lowercase version of the project name useful for comparison or indexing extras A tuple of names of extras that this requirement calls for These will be all lowercase and normalized using the safe extra parsing utility function so they may not exactly equal the extras the requirement was created with specs A list of op version tuples sorted in ascending parsed version order The op in each tuple is a comparison operator represented as a string The version is the unparsed version number The relative order of tuples containing the same version numbers is undefined since having more than one operator for a given version is either redundant or self contradictory Entry Points Entry points are a simple way for distributions to advertise Python objects such as functions or classes for use by other distributions Extensible applications and frameworks can search for entry points with a particular name or group either from a specific distribution or from all active distributions on sys path and then inspect or load the advertised objects at will Entry points belong to groups which are named with a dotted name similar to a Python package or module name For example the setuptools package uses an entry point named distutils commands in order to find commands defined by distutils extensions setuptools treats the names of entry points defined in that group as the acceptable commands for a setup script In a similar way other packages can define their own entry point groups either using dynamic names within the group like distutils commands or possibly using predefined names within the group For example a blogging framework that offers various pre or post publishing hooks might define an entry point group and look for entry points named pre process and post process within that group To advertise an entry point a project needs to use setuptools and provide an entry points argument to setup in its setup script so that the entry points will be included in the distribution s metadata For more details see the setuptools documentation XXX link here to setuptools Each project distribution can advertise at most one entry point of a given name within the same entry point group For example a distutils extension could advertise two different distutils commands entry points as long as they had different names However there is nothing that prevents different projects from advertising entry points of the same name in the same group In some cases this is a desirable thing since the application or framework that uses the entry points may be calling them as hooks or in some other way combining them It is up to the application or framework to decide what to do if multiple distributions advertise an entry point some possibilities include using both entry points displaying an error message using the first one found in sys path order etc Convenience API In the following functions the dist argument can be a Distribution instance a Requirement instance or a string specifying a requirement i e project name version etc If the argument is a string or Requirement the specified distribution is located and added to sys path if not already present An error will be raised if a matching distribution is not available The group argument should be a string containing a dotted identifier identifying an entry point group If you are defining an entry point group you should include some portion of your package s name in the group name so as to avoid collision with other packages entry point groups load entry point dist group name Load the named entry point from the specified distribution or raise ImportError get entry info dist group name Return an EntryPoint object for the given group and name from the specified distribution Returns None if the distribution has not advertised a matching entry point get entry map dist group None Return the distribution s entry point map for group or the full entry map for the distribution This function always returns a dictionary even if the distribution advertises no entry points If group is given the dictionary maps entry point names to the corresponding EntryPoint object If group is None the dictionary maps group names to dictionaries that then map entry point names to the corresponding EntryPoint instance in that group iter entry points group name None 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 on sys path otherwise only ones matching both group and name are yielded Entry points are yielded from the active distributions in the order that the distributions appear on sys path Within entry points for a particular distribution however there is no particular ordering This API is actually a method of the global working set object see the section above on Basic WorkingSet Methods for more information Creating and Parsing EntryPoint name module name attrs extras dist None Create an EntryPoint instance name is the entry point name The module name is the dotted name of the module containing the advertised object attrs is an optional tuple of names to look up from the module to obtain the advertised object For example an attrs of foo bar and a module name of baz would mean that the advertised object could be obtained by the following code import baz advertised object baz foo bar The extras are an optional tuple of extra feature names that the distribution needs in order to provide this entry point When the entry point is loaded these extra features are looked up in the dist argument to find out what other distributions may need to be activated on sys path see the load method for more details The extras argument is only meaningful if dist is specified dist must be a Distribution instance EntryPoint parse src dist None classmethod 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 as is the whitespace shown between some of the items The dist argument is passed through to the EntryPoint constructor along with the other values parsed from src EntryPoint parse group group lines dist None classmethod Parse lines a string or sequence of lines to create a dictionary mapping entry point names to EntryPoint objects ValueError is raised if entry point names are duplicated if group is not a valid entry point group name or if there are any syntax errors Note the group parameter is used only for validation and to create more informative error messages If dist is provided it will be used to set the dist attribute of the created EntryPoint objects EntryPoint parse map data dist None classmethod Parse data into a dictionary mapping group names to dictionaries mapping entry point names to EntryPoint objects If data is a dictionary then the keys are used as group names and the values are passed to parse group as the lines argument If data is a string or sequence of lines it is first split into ini style sections using the split sections utility function and the section names are used as group names In either case the dist argument is passed through to parse group so that the entry points will be linked to the specified distribution EntryPoint Objects For simple introspection EntryPoint objects have attributes that correspond exactly to the constructor argument names name module name attrs extras and dist are all available In addition the following methods are provided load require True env None installer None Load the entry point returning the advertised Python object or raise ImportError if it cannot be obtained If require is a true value then require env installer is called before attempting the import require env None installer None Ensure that any extras needed by the entry point are available on sys path UnknownExtra is raised if the EntryPoint has extras but no dist or if the named extras are not defined by the distribution If env is supplied it must be an Environment and it will be used to search for needed distributions if they are not already present on sys path If installer is supplied it must be a callable taking a Requirement instance and returning a matching importable Distribution instance or None str The string form of an EntryPoint is a string that could be passed to EntryPoint parse to produce an equivalent EntryPoint Distribution Objects Distribution objects represent collections of Python code that may or may not be importable and may or may not have metadata and resources associated with them Their metadata may include information such as what other projects the distribution depends on what entry points the distribution advertises and so on Getting or Creating Distributions Most commonly you ll obtain Distribution objects from a WorkingSet or an Environment See the sections above on WorkingSet Objects and Environment Objects which are containers for active distributions and available distributions respectively You can also obtain Distribution objects from one of these high level APIs find distributions path item only False Yield distributions accessible via path item If only is true yield only distributions whose location is equal to path item In other words if only is true this yields any distributions that would be importable if path item were on sys path If only is false this also yields distributions that are in or under path item but would not be importable unless their locations were also added to sys path get distribution dist spec Return a Distribution object for a given Requirement or string If dist spec is already a Distribution instance it is returned If it is a Requirement object or a string that can be parsed into one it is used to locate and activate a matching distribution which is then returned However if you re creating specialized tools for working with distributions or creating a new distribution format you may also need to create Distribution objects directly using one of the three constructors below These constructors all take an optional metadata argument which is used to access any resources or metadata associated with the distribution metadata must be an object that implements the IResourceProvider interface or None If it is None an EmptyProvider is used instead Distribution objects implement both the IResourceProvider and IMetadataProvider Methods by delegating them to the metadata object Distribution from location location basename metadata None kw classmethod Create a distribution for location which must be a string such as a URL filename or other string that might be used on sys path basename is a string naming the distribution like Foo 1 2 py2 4 egg If basename ends with egg then the project s name version python version and platform are extracted from the filename and used to set those properties of the created distribution Any additional keyword arguments are forwarded to the Distribution constructor Distribution from filename filename metadata None kw classmethod Create a distribution by parsing a local filename This is a shorter way of saying Distribution from location normalize path filename os path basename filename metadata In other words it creates a distribution whose location is the normalize form of the filename parsing name and version information from the base portion of the filename Any additional keyword arguments are forwarded to the Distribution constructor Distribution location metadata project name version py version platform precedence Create a distribution by setting its properties All arguments are optional and default to None except for py version which defaults to the current Python version and precedence which defaults to EGG DIST for more details see precedence under Distribution Attributes below Note that it s usually easier to use the from filename or from location constructors than to specify all these arguments individually Distribution Attributes location A string indicating the distribution s location For an importable distribution this is the string that would be added to sys path to make it actively importable For non importable distributions this is simply a filename URL or other way of locating the distribution project name A string naming the project that this distribution is for Project names are defined by a project s setup script and they are used to identify projects on PyPI When a Distribution is constructed the project name argument is passed through the safe name utility function to filter out any unacceptable characters key dist key is short for dist project name lower It s used for case insensitive comparison and indexing of distributions by project name extras A list of strings giving the names of extra features defined by the project s dependency list the extras require argument specified in the project s setup script version A string denoting what release of the project this distribution contains When a Distribution is constructed the version argument is passed through the safe version utility function to filter out any unacceptable characters If no version is specified at construction time then attempting to access this attribute later will cause the Distribution to try to discover its version by reading its PKG INFO metadata file If PKG INFO is unavailable or can t be parsed ValueError is raised parsed version The parsed version is a tuple representing a parsed form of the distribution s version dist parsed version is a shortcut for calling parse version dist version It is used to compare or sort distributions by version See the Parsing Utilities section below for more information on the parse version function Note that accessing parsed version may result in a ValueError if the Distribution was constructed without a version and without metadata capable of supplying the missing version info py version The major minor Python version the distribution supports as a string For example 2 3 or 2 4 The default is the current version of Python platform A string representing the platform the distribution is intended for or None if the distribution is pure Python and therefore cross platform See Platform Utilities below for more information on platform strings precedence A distribution s precedence is used to determine the relative order of two distributions that have the same project name and parsed version The default precedence is pkg resources EGG DIST which is the highest i e most preferred precedence The full list of predefined precedences from most preferred to least preferred is EGG DIST BINARY DIST SOURCE DIST CHECKOUT DIST and DEVELOP DIST Normally precedences other than EGG DIST are used only by the setuptools package index module when sorting distributions found in a package index to determine their suitability for installation System and Development eggs i e ones that use the egg info format however are automatically given a precedence of DEVELOP DIST Distribution Methods activate path None Ensure distribution is importable on path If path is None sys path is used instead This ensures that the distribution s location is in the path list and it also performs any necessary namespace package fixups or declarations That is if the distribution contains namespace packages this method ensures that they are declared and that the distribution s contents for those namespace packages are merged with the contents provided by any other active distributions See the section above on Namespace Package Support for more information pkg resources adds a notification callback to the global working set that ensures this method is called whenever a distribution is added to it Therefore you should not normally need to explicitly call this method Note that this means that namespace packages on sys path are always imported as soon as pkg resources is which is another reason why namespace packages should not contain any code or import statements as requirement Return a Requirement instance that matches this distribution s project name and version requires extras List the Requirement objects that specify this distribution s dependencies If extras is specified it should be a sequence of names of extras defined by the distribution and the list returned will then include any dependencies needed to support the named extras clone kw Create a copy of the distribution Any supplied keyword arguments override the corresponding argument to the Distribution constructor allowing you to change some of the copied distribution s attributes egg name Return what this distribution s standard filename should be not including the egg extension For example a distribution for project Foo version 1 2 that runs on Python 2 3 for Windows would have an egg name of Foo 1 2 py2 3 win32 Any dashes in the name or version are converted to underscores Distribution from location will convert them back when parsing a egg file name cmp other hash Distribution objects are hashed and compared on the basis of their parsed version and precedence followed by their key lowercase project name location Python version and platform The following methods are used to access EntryPoint objects advertised by the distribution See the section above on Entry Points for more detailed information about these operations get entry info group name Return the EntryPoint object for group and name or None if no such point is advertised by this distribution get entry map group None Return the entry point map for group If group is None return a dictionary mapping group names to entry point maps for all groups An entry point map is a dictionary of entry point names to EntryPoint objects load entry point group name Short for get entry info group name load Returns the object advertised by the named entry point or raises ImportError if the entry point isn t advertised by this distribution or there is some other import problem In addition to the above methods Distribution objects also implement all of the IResourceProvider and IMetadataProvider Methods which are documented in later sections has metadata name metadata isdir name metadata listdir name get metadata name get metadata lines name run script script name namespace get resource filename manager resource name get resource stream manager resource name get resource string manager resource name has resource resource name resource isdir resource name resource listdir resource name If the distribution was created with a metadata argument these resource and metadata access methods are all delegated to that metadata provider Otherwise they are delegated to an EmptyProvider so that the distribution will appear to have no resources or metadata This delegation approach is used so that supporting custom importers or new distribution formats can be done simply by creating an appropriate IResourceProvider implementation see the section below on Supporting Custom Importers for more details ResourceManager API The ResourceManager class provides uniform access to package resources whether those resources exist as files and directories or are compressed in an archive of some kind Normally you do not need to create or explicitly manage ResourceManager instances as the pkg resources module creates a global instance for you and makes most of its methods available as top level names in the pkg resources module namespace So for example this code actually calls the resource string method of the global ResourceManager import pkg resources my data pkg resources resource string name foo dat Thus you can use the APIs below without needing an explicit ResourceManager instance just import and use them as needed Basic Resource Access In the following methods the package or requirement argument may be either a Python package module name e g foo bar or a Requirement instance If it is a package or module name the named module or package must be importable i e be in a distribution or directory on sys path and the resource name argument is interpreted relative to the named package Note that if a module name is used then the resource name is relative to the package immediately containing the named module Also you should not use use a namespace package name because a namespace package can be spread across multiple distributions and is therefore ambiguous as to which distribution should be searched for the resource If it is a Requirement then the requirement is automatically resolved searching the current Environment if necessary and a matching distribution is added to the WorkingSet and sys path if one was not already present Unless the Requirement can t be satisfied in which case an exception is raised The resource name argument is then interpreted relative to the root of the identified distribution i e its first path segment will be treated as a peer of the top level modules or packages in the distribution Note that resource names must be separated paths and cannot be absolute i e no leading or contain relative names like Do not use os path routines to manipulate resource paths as they are not filesystem paths resource exists package or requirement resource name Does the named resource exist Return True or False accordingly resource stream package or requirement resource name Return a readable file like object for the specified resource it may be an actual file a StringIO or some similar object The stream is in binary mode in the sense that whatever bytes are in the resource will be read as is resource string package or requirement resource name Return the specified resource as a string The resource is read in binary fashion such that the returned string contains exactly the bytes that are stored in the resource resource isdir package or requirement resource name Is the named resource a directory Return True or False accordingly resource listdir package or requirement resource name List the contents of the named resource directory just like os listdir except that it works even if the resource is in a zipfile Note that only resource exists and resource isdir are insensitive as to the resource type You cannot use resource listdir on a file resource and you can t use resource string or resource stream on directory resources Using an inappropriate method for the resource type may result in an exception or undefined behavior depending on the platform and distribution format involved Resource Extraction resource filename package or requirement resource name Sometimes it is not sufficient to access a resource in string or stream form and a true filesystem filename is needed In such cases you can use this method or module level function to obtain a filename for a resource If the resource is in an archive distribution such as a zipped egg it will be extracted to a cache directory and the filename within the cache will be returned If the named resource is a directory then all resources within that directory including subdirectories are also extracted If the named resource is a C extension or eager resource see the setuptools documentation for details then all C extensions and eager resources are extracted at the same time Archived resources are extracted to a cache location that can be managed by the following two methods set extraction path path 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 resource provider 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 On Windows for example you can t unlink pyd or dll files that are still in use Note that you may not change the extraction path for a given resource manager once resources have been extracted unless you first call cleanup resources cleanup resources force False 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 Provider Interface If you are implementing an IResourceProvider and or IMetadataProvider for a new distribution archive format you may need to use the following IResourceManager methods to co ordinate extraction of resources to the filesystem If you re not implementing an archive format however you have no need to use these methods Unlike the other methods listed above they are not available as top level functions tied to the global ResourceManager you must therefore have an explicit ResourceManager instance to use them get cache path archive name names 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 extraction error Raise an ExtractionError describing the active exception as interfering with the extraction process You should call this if you encounter any OS errors extracting the file to the cache path it will format the operating system exception for you and add other information to the ExtractionError instance that may be needed by programs that want to wrap or handle extraction errors themselves postprocess tempname filename Perform any platform specific postprocessing of tempname 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 Metadata API The metadata API is used to access metadata resources bundled in a pluggable distribution Metadata resources are virtual files or directories containing information about the distribution such as might be used by an extensible application or framework to connect plugins Like other kinds of resources metadata resource names are separated and should not contain or begin with a You should not use os path routines to manipulate resource paths The metadata API is provided by objects implementing the IMetadataProvider or IResourceProvider interfaces Distribution objects implement this interface as do objects returned by the get provider function get provider package or requirement If a package name is supplied return an IResourceProvider for the package If a Requirement is supplied resolve it by returning a Distribution from the current working set searching the current Environment if necessary and adding the newly found Distribution to the working set If the named package can t be imported or the Requirement can t be satisfied an exception is raised NOTE if you use a package name rather than a Requirement the object you get back may not be a pluggable distribution depending on the method by which the package was installed In particular development packages and single version externally managed packages do not have any way to map from a package name to the corresponding project s metadata Do not write code that passes a package name to get provider and then tries to retrieve project metadata from the returned object It may appear to work when the named package is in an egg file or directory but it will fail in other installation scenarios If you want project metadata you need to ask for a project not a package IMetadataProvider Methods The methods provided by objects such as Distribution instances that implement the IMetadataProvider or IResourceProvider interfaces are has metadata name Does the named metadata resource exist metadata isdir name Is the named metadata resource a directory metadata listdir name List of metadata names in the directory like os listdir get metadata name Return the named metadata resource as a string The data is read in binary mode i e the exact bytes of the resource file are returned get metadata lines name Yield named metadata resource as list of non blank non comment lines This is short for calling yield lines provider get metadata name See the section on yield lines below for more information on the syntax it recognizes run script script name namespace Execute the named script in the supplied namespace dictionary Raises ResolutionError if there is no script by that name in the scripts metadata directory namespace should be a Python dictionary usually a module dictionary if the script is being run as a module Exceptions pkg resources provides a simple exception hierarchy for problems that may occur when processing requests to locate and activate packages ResolutionError DistributionNotFound VersionConflict UnknownExtra ExtractionError ResolutionError This class is used as a base class for the other three exceptions so that you can catch all of them with a single except clause It is also raised directly for miscellaneous requirement resolution problems like trying to run a script that doesn t exist in the distribution it was requested from DistributionNotFound A distribution needed to fulfill a requirement could not be found VersionConflict The requested version of a project conflicts with an already activated version of the same project UnknownExtra One of the extras requested was not recognized by the distribution it was requested from ExtractionError A problem occurred extracting a resource to the Python Egg cache The following attributes are available on instances of this exception manager The resource manager that raised this exception cache path The base directory for resource extraction original error The exception instance that caused extraction to fail Supporting Custom Importers By default pkg resources supports normal filesystem imports and zipimport importers If you wish to use the pkg resources features with other PEP 302 compatible importers or module loaders you may need to register various handlers and support functions using these APIs register finder importer type distribution finder 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 when passed a path item the importer instance and an only flag yields Distribution instances found under that path item The only flag if true means the finder should yield only Distribution objects whose location is equal to the path item provided See the source of the pkg resources find on path function for an example finder function register loader type loader type provider factory Register provider factory to make IResourceProvider objects for loader type loader type is the type or class of a PEP 302 module loader and provider factory is a function that when passed a module object returns an IResourceProvider for that module allowing it to be used with the ResourceManager API register namespace handler importer type namespace handler Register namespace handler to declare namespace packages for the given importer type importer type is the type or class of a PEP 302 importer sys path item handler and namespace handler is a callable with a signature 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 relevant importer object has already agreed that it can handle the relevant path item The handler should only return a subpath if the module path does not already contain an equivalent subpath Otherwise it should return None For an example namespace handler see the source of the pkg resources file ns handler function which is used for

    Original URL path: http://peak.telecommunity.com/DevCenter/PkgResources?action=edit (2016-04-24)
    Open archived version from archive

  • PkgResources - The PEAK Developers' Center
    initialization are added This method is a shortcut for using the find distributions function to find the distributions from each item in search path and then calling add to add each one to the environment Requirement Objects Requirement objects express what versions of a project are suitable for some purpose These objects or their string form are used by various pkg resources APIs in order to find distributions that a script or distribution needs Requirements Parsing parse requirements s Yield Requirement objects for a string or iterable of lines Each requirement must start on a new line See below for syntax Requirement parse s Create a Requirement object from a string or iterable of lines A ValueError is raised if the string or lines do not contain a valid requirement specifier or if they contain more than one specifier To parse multiple specifiers from a string or iterable of strings use parse requirements instead The syntax of a requirement specifier can be defined in EBNF as follows requirement project name versionspec extras versionspec comparison version comparison version comparison extras extralist extralist identifier identifier project name identifier identifier A Za z0 9 version A Za z0 9 Tokens can be separated by whitespace and a requirement can be continued over multiple lines using a backslash Line end comments using are also allowed Some examples of valid requirement specifiers FooProject 1 2 Fizzy foo bar PickyThing 1 6 1 9 1 9 6 2 0a0 2 4c1 SomethingWhoseVersionIDontCareAbout The project name is the only required portion of a requirement string and if it s the only thing supplied the requirement will accept any version of that project The extras in a requirement are used to request optional features of a project that may require additional project distributions in order to function For example if the hypothetical Report O Rama project offered optional PDF support it might require an additional library in order to provide that support Thus a project needing Report O Rama s PDF features could use a requirement of Report O Rama PDF to request installation or activation of both Report O Rama and any libraries it needs in order to provide PDF support For example you could use easy install py Report O Rama PDF To install the necessary packages using the EasyInstall program or call pkg resources require Report O Rama PDF to add the necessary distributions to sys path at runtime Requirement Methods and Attributes contains dist or version Return true if dist or version fits the criteria for this requirement If dist or version is a Distribution object its project name must match the requirement s project name and its version must meet the requirement s version criteria If dist or version is a string it is parsed using the parse version utility function Otherwise it is assumed to be an already parsed version The Requirement object s version specifiers specs are internally sorted into ascending version order and used to establish what ranges of versions are acceptable Adjacent redundant conditions are effectively consolidated e g 1 2 produces the same results as 1 and 2 3 produces the same results as 3 versions are excised from the ranges they fall within The version being tested for acceptability is then checked for membership in the resulting ranges Note that providing conflicting conditions for the same version e g 2 2 or 2 2 is meaningless and may therefore produce bizarre results when compared with actual version number s eq other requirement A requirement compares equal to another requirement if they have case insensitively equal project names version specifiers and extras The order that extras and version specifiers are in is also ignored Equal requirements also have equal hashes so that requirements can be used in sets or as dictionary keys str The string form of a Requirement is a string that if passed to Requirement parse would return an equal Requirement object project name The name of the required project key An all lowercase version of the project name useful for comparison or indexing extras A tuple of names of extras that this requirement calls for These will be all lowercase and normalized using the safe extra parsing utility function so they may not exactly equal the extras the requirement was created with specs A list of op version tuples sorted in ascending parsed version order The op in each tuple is a comparison operator represented as a string The version is the unparsed version number The relative order of tuples containing the same version numbers is undefined since having more than one operator for a given version is either redundant or self contradictory Entry Points Entry points are a simple way for distributions to advertise Python objects such as functions or classes for use by other distributions Extensible applications and frameworks can search for entry points with a particular name or group either from a specific distribution or from all active distributions on sys path and then inspect or load the advertised objects at will Entry points belong to groups which are named with a dotted name similar to a Python package or module name For example the setuptools package uses an entry point named distutils commands in order to find commands defined by distutils extensions setuptools treats the names of entry points defined in that group as the acceptable commands for a setup script In a similar way other packages can define their own entry point groups either using dynamic names within the group like distutils commands or possibly using predefined names within the group For example a blogging framework that offers various pre or post publishing hooks might define an entry point group and look for entry points named pre process and post process within that group To advertise an entry point a project needs to use setuptools and provide an entry points argument to setup in its setup script so that the entry points will be included in the distribution s metadata For more details see the setuptools documentation XXX link here to setuptools Each project distribution can advertise at most one entry point of a given name within the same entry point group For example a distutils extension could advertise two different distutils commands entry points as long as they had different names However there is nothing that prevents different projects from advertising entry points of the same name in the same group In some cases this is a desirable thing since the application or framework that uses the entry points may be calling them as hooks or in some other way combining them It is up to the application or framework to decide what to do if multiple distributions advertise an entry point some possibilities include using both entry points displaying an error message using the first one found in sys path order etc Convenience API In the following functions the dist argument can be a Distribution instance a Requirement instance or a string specifying a requirement i e project name version etc If the argument is a string or Requirement the specified distribution is located and added to sys path if not already present An error will be raised if a matching distribution is not available The group argument should be a string containing a dotted identifier identifying an entry point group If you are defining an entry point group you should include some portion of your package s name in the group name so as to avoid collision with other packages entry point groups load entry point dist group name Load the named entry point from the specified distribution or raise ImportError get entry info dist group name Return an EntryPoint object for the given group and name from the specified distribution Returns None if the distribution has not advertised a matching entry point get entry map dist group None Return the distribution s entry point map for group or the full entry map for the distribution This function always returns a dictionary even if the distribution advertises no entry points If group is given the dictionary maps entry point names to the corresponding EntryPoint object If group is None the dictionary maps group names to dictionaries that then map entry point names to the corresponding EntryPoint instance in that group iter entry points group name None 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 on sys path otherwise only ones matching both group and name are yielded Entry points are yielded from the active distributions in the order that the distributions appear on sys path Within entry points for a particular distribution however there is no particular ordering This API is actually a method of the global working set object see the section above on Basic WorkingSet Methods for more information Creating and Parsing EntryPoint name module name attrs extras dist None Create an EntryPoint instance name is the entry point name The module name is the dotted name of the module containing the advertised object attrs is an optional tuple of names to look up from the module to obtain the advertised object For example an attrs of foo bar and a module name of baz would mean that the advertised object could be obtained by the following code import baz advertised object baz foo bar The extras are an optional tuple of extra feature names that the distribution needs in order to provide this entry point When the entry point is loaded these extra features are looked up in the dist argument to find out what other distributions may need to be activated on sys path see the load method for more details The extras argument is only meaningful if dist is specified dist must be a Distribution instance EntryPoint parse src dist None classmethod 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 as is the whitespace shown between some of the items The dist argument is passed through to the EntryPoint constructor along with the other values parsed from src EntryPoint parse group group lines dist None classmethod Parse lines a string or sequence of lines to create a dictionary mapping entry point names to EntryPoint objects ValueError is raised if entry point names are duplicated if group is not a valid entry point group name or if there are any syntax errors Note the group parameter is used only for validation and to create more informative error messages If dist is provided it will be used to set the dist attribute of the created EntryPoint objects EntryPoint parse map data dist None classmethod Parse data into a dictionary mapping group names to dictionaries mapping entry point names to EntryPoint objects If data is a dictionary then the keys are used as group names and the values are passed to parse group as the lines argument If data is a string or sequence of lines it is first split into ini style sections using the split sections utility function and the section names are used as group names In either case the dist argument is passed through to parse group so that the entry points will be linked to the specified distribution EntryPoint Objects For simple introspection EntryPoint objects have attributes that correspond exactly to the constructor argument names name module name attrs extras and dist are all available In addition the following methods are provided load require True env None installer None Load the entry point returning the advertised Python object or raise ImportError if it cannot be obtained If require is a true value then require env installer is called before attempting the import require env None installer None Ensure that any extras needed by the entry point are available on sys path UnknownExtra is raised if the EntryPoint has extras but no dist or if the named extras are not defined by the distribution If env is supplied it must be an Environment and it will be used to search for needed distributions if they are not already present on sys path If installer is supplied it must be a callable taking a Requirement instance and returning a matching importable Distribution instance or None str The string form of an EntryPoint is a string that could be passed to EntryPoint parse to produce an equivalent EntryPoint Distribution Objects Distribution objects represent collections of Python code that may or may not be importable and may or may not have metadata and resources associated with them Their metadata may include information such as what other projects the distribution depends on what entry points the distribution advertises and so on Getting or Creating Distributions Most commonly you ll obtain Distribution objects from a WorkingSet or an Environment See the sections above on WorkingSet Objects and Environment Objects which are containers for active distributions and available distributions respectively You can also obtain Distribution objects from one of these high level APIs find distributions path item only False Yield distributions accessible via path item If only is true yield only distributions whose location is equal to path item In other words if only is true this yields any distributions that would be importable if path item were on sys path If only is false this also yields distributions that are in or under path item but would not be importable unless their locations were also added to sys path get distribution dist spec Return a Distribution object for a given Requirement or string If dist spec is already a Distribution instance it is returned If it is a Requirement object or a string that can be parsed into one it is used to locate and activate a matching distribution which is then returned However if you re creating specialized tools for working with distributions or creating a new distribution format you may also need to create Distribution objects directly using one of the three constructors below These constructors all take an optional metadata argument which is used to access any resources or metadata associated with the distribution metadata must be an object that implements the IResourceProvider interface or None If it is None an EmptyProvider is used instead Distribution objects implement both the IResourceProvider and IMetadataProvider Methods by delegating them to the metadata object Distribution from location location basename metadata None kw classmethod Create a distribution for location which must be a string such as a URL filename or other string that might be used on sys path basename is a string naming the distribution like Foo 1 2 py2 4 egg If basename ends with egg then the project s name version python version and platform are extracted from the filename and used to set those properties of the created distribution Any additional keyword arguments are forwarded to the Distribution constructor Distribution from filename filename metadata None kw classmethod Create a distribution by parsing a local filename This is a shorter way of saying Distribution from location normalize path filename os path basename filename metadata In other words it creates a distribution whose location is the normalize form of the filename parsing name and version information from the base portion of the filename Any additional keyword arguments are forwarded to the Distribution constructor Distribution location metadata project name version py version platform precedence Create a distribution by setting its properties All arguments are optional and default to None except for py version which defaults to the current Python version and precedence which defaults to EGG DIST for more details see precedence under Distribution Attributes below Note that it s usually easier to use the from filename or from location constructors than to specify all these arguments individually Distribution Attributes location A string indicating the distribution s location For an importable distribution this is the string that would be added to sys path to make it actively importable For non importable distributions this is simply a filename URL or other way of locating the distribution project name A string naming the project that this distribution is for Project names are defined by a project s setup script and they are used to identify projects on PyPI When a Distribution is constructed the project name argument is passed through the safe name utility function to filter out any unacceptable characters key dist key is short for dist project name lower It s used for case insensitive comparison and indexing of distributions by project name extras A list of strings giving the names of extra features defined by the project s dependency list the extras require argument specified in the project s setup script version A string denoting what release of the project this distribution contains When a Distribution is constructed the version argument is passed through the safe version utility function to filter out any unacceptable characters If no version is specified at construction time then attempting to access this attribute later will cause the Distribution to try to discover its version by reading its PKG INFO metadata file If PKG INFO is unavailable or can t be parsed ValueError is raised parsed version The parsed version is a tuple representing a parsed form of the distribution s version dist parsed version is a shortcut for calling parse version dist version It is used to compare or sort distributions by version See the Parsing Utilities section below for more information on the parse version function Note that accessing parsed version may result in a ValueError if the Distribution was constructed without a version and without metadata capable of supplying the missing version info py version The major minor Python version the distribution supports as a string For example 2 3 or 2 4 The default is the current version of Python platform A string representing the platform the distribution is intended for or None if the distribution is pure Python and therefore cross platform See Platform Utilities below for more information on platform strings precedence A distribution s precedence is used to determine the relative order of two distributions that have the same project name and parsed version The default precedence is pkg resources EGG DIST which is the highest i e most preferred precedence The full list of predefined precedences from most preferred to least preferred is EGG DIST BINARY DIST SOURCE DIST CHECKOUT DIST and DEVELOP DIST Normally precedences other than EGG DIST are used only by the setuptools package index module when sorting distributions found in a package index to determine their suitability for installation System and Development eggs i e ones that use the egg info format however are automatically given a precedence of DEVELOP DIST Distribution Methods activate path None Ensure distribution is importable on path If path is None sys path is used instead This ensures that the distribution s location is in the path list and it also performs any necessary namespace package fixups or declarations That is if the distribution contains namespace packages this method ensures that they are declared and that the distribution s contents for those namespace packages are merged with the contents provided by any other active distributions See the section above on Namespace Package Support for more information pkg resources adds a notification callback to the global working set that ensures this method is called whenever a distribution is added to it Therefore you should not normally need to explicitly call this method Note that this means that namespace packages on sys path are always imported as soon as pkg resources is which is another reason why namespace packages should not contain any code or import statements as requirement Return a Requirement instance that matches this distribution s project name and version requires extras List the Requirement objects that specify this distribution s dependencies If extras is specified it should be a sequence of names of extras defined by the distribution and the list returned will then include any dependencies needed to support the named extras clone kw Create a copy of the distribution Any supplied keyword arguments override the corresponding argument to the Distribution constructor allowing you to change some of the copied distribution s attributes egg name Return what this distribution s standard filename should be not including the egg extension For example a distribution for project Foo version 1 2 that runs on Python 2 3 for Windows would have an egg name of Foo 1 2 py2 3 win32 Any dashes in the name or version are converted to underscores Distribution from location will convert them back when parsing a egg file name cmp other hash Distribution objects are hashed and compared on the basis of their parsed version and precedence followed by their key lowercase project name location Python version and platform The following methods are used to access EntryPoint objects advertised by the distribution See the section above on Entry Points for more detailed information about these operations get entry info group name Return the EntryPoint object for group and name or None if no such point is advertised by this distribution get entry map group None Return the entry point map for group If group is None return a dictionary mapping group names to entry point maps for all groups An entry point map is a dictionary of entry point names to EntryPoint objects load entry point group name Short for get entry info group name load Returns the object advertised by the named entry point or raises ImportError if the entry point isn t advertised by this distribution or there is some other import problem In addition to the above methods Distribution objects also implement all of the IResourceProvider and IMetadataProvider Methods which are documented in later sections has metadata name metadata isdir name metadata listdir name get metadata name get metadata lines name run script script name namespace get resource filename manager resource name get resource stream manager resource name get resource string manager resource name has resource resource name resource isdir resource name resource listdir resource name If the distribution was created with a metadata argument these resource and metadata access methods are all delegated to that metadata provider Otherwise they are delegated to an EmptyProvider so that the distribution will appear to have no resources or metadata This delegation approach is used so that supporting custom importers or new distribution formats can be done simply by creating an appropriate IResourceProvider implementation see the section below on Supporting Custom Importers for more details ResourceManager API The ResourceManager class provides uniform access to package resources whether those resources exist as files and directories or are compressed in an archive of some kind Normally you do not need to create or explicitly manage ResourceManager instances as the pkg resources module creates a global instance for you and makes most of its methods available as top level names in the pkg resources module namespace So for example this code actually calls the resource string method of the global ResourceManager import pkg resources my data pkg resources resource string name foo dat Thus you can use the APIs below without needing an explicit ResourceManager instance just import and use them as needed Basic Resource Access In the following methods the package or requirement argument may be either a Python package module name e g foo bar or a Requirement instance If it is a package or module name the named module or package must be importable i e be in a distribution or directory on sys path and the resource name argument is interpreted relative to the named package Note that if a module name is used then the resource name is relative to the package immediately containing the named module Also you should not use use a namespace package name because a namespace package can be spread across multiple distributions and is therefore ambiguous as to which distribution should be searched for the resource If it is a Requirement then the requirement is automatically resolved searching the current Environment if necessary and a matching distribution is added to the WorkingSet and sys path if one was not already present Unless the Requirement can t be satisfied in which case an exception is raised The resource name argument is then interpreted relative to the root of the identified distribution i e its first path segment will be treated as a peer of the top level modules or packages in the distribution Note that resource names must be separated paths and cannot be absolute i e no leading or contain relative names like Do not use os path routines to manipulate resource paths as they are not filesystem paths resource exists package or requirement resource name Does the named resource exist Return True or False accordingly resource stream package or requirement resource name Return a readable file like object for the specified resource it may be an actual file a StringIO or some similar object The stream is in binary mode in the sense that whatever bytes are in the resource will be read as is resource string package or requirement resource name Return the specified resource as a string The resource is read in binary fashion such that the returned string contains exactly the bytes that are stored in the resource resource isdir package or requirement resource name Is the named resource a directory Return True or False accordingly resource listdir package or requirement resource name List the contents of the named resource directory just like os listdir except that it works even if the resource is in a zipfile Note that only resource exists and resource isdir are insensitive as to the resource type You cannot use resource listdir on a file resource and you can t use resource string or resource stream on directory resources Using an inappropriate method for the resource type may result in an exception or undefined behavior depending on the platform and distribution format involved Resource Extraction resource filename package or requirement resource name Sometimes it is not sufficient to access a resource in string or stream form and a true filesystem filename is needed In such cases you can use this method or module level function to obtain a filename for a resource If the resource is in an archive distribution such as a zipped egg it will be extracted to a cache directory and the filename within the cache will be returned If the named resource is a directory then all resources within that directory including subdirectories are also extracted If the named resource is a C extension or eager resource see the setuptools documentation for details then all C extensions and eager resources are extracted at the same time Archived resources are extracted to a cache location that can be managed by the following two methods set extraction path path 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 resource provider 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 On Windows for example you can t unlink pyd or dll files that are still in use Note that you may not change the extraction path for a given resource manager once resources have been extracted unless you first call cleanup resources cleanup resources force False 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 Provider Interface If you are implementing an IResourceProvider and or IMetadataProvider for a new distribution archive format you may need to use the following IResourceManager methods to co ordinate extraction of resources to the filesystem If you re not implementing an archive format however you have no need to use these methods Unlike the other methods listed above they are not available as top level functions tied to the global ResourceManager you must therefore have an explicit ResourceManager instance to use them get cache path archive name names 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 extraction error Raise an ExtractionError describing the active exception as interfering with the extraction process You should call this if you encounter any OS errors extracting the file to the cache path it will format the operating system exception for you and add other information to the ExtractionError instance that may be needed by programs that want to wrap or handle extraction errors themselves postprocess tempname filename Perform any platform specific postprocessing of tempname 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 Metadata API The metadata API is used to access metadata resources bundled in a pluggable distribution Metadata resources are virtual files or directories containing information about the distribution such as might be used by an extensible application or framework to connect plugins Like other kinds of resources metadata resource names are separated and should not contain or begin with a You should not use os path routines to manipulate resource paths The metadata API is provided by objects implementing the IMetadataProvider or IResourceProvider interfaces Distribution objects implement this interface as do objects returned by the get provider function get provider package or requirement If a package name is supplied return an IResourceProvider for the package If a Requirement is supplied resolve it by returning a Distribution from the current working set searching the current Environment if necessary and adding the newly found Distribution to the working set If the named package can t be imported or the Requirement can t be satisfied an exception is raised NOTE if you use a package name rather than a Requirement the object you get back may not be a pluggable distribution depending on the method by which the package was installed In particular development packages and single version externally managed packages do not have any way to map from a package name to the corresponding project s metadata Do not write code that passes a package name to get provider and then tries to retrieve project metadata from the returned object It may appear to work when the named package is in an egg file or directory but it will fail in other installation scenarios If you want project metadata you need to ask for a project not a package IMetadataProvider Methods The methods provided by objects such as Distribution instances that implement the IMetadataProvider or IResourceProvider interfaces are has metadata name Does the named metadata resource exist metadata isdir name Is the named metadata resource a directory metadata listdir name List of metadata names in the directory like os listdir get metadata name Return the named metadata resource as a string The data is read in binary mode i e the exact bytes of the resource file are returned get metadata lines name Yield named metadata resource as list of non blank non comment lines This is short for calling yield lines provider get metadata name See the section on yield lines below for more information on the syntax it recognizes run script script name namespace Execute the named script in the supplied namespace dictionary Raises ResolutionError if there is no script by that name in the scripts metadata directory namespace should be a Python dictionary usually a module dictionary if the script is being run as a module Exceptions pkg resources provides a simple exception hierarchy for problems that may occur when processing requests to locate and activate packages ResolutionError DistributionNotFound VersionConflict UnknownExtra ExtractionError ResolutionError This class is used as a base class for the other three exceptions so that you can catch all of them with a single except clause It is also raised directly for miscellaneous requirement resolution problems like trying to run a script that doesn t exist in the distribution it was requested from DistributionNotFound A distribution needed to fulfill a requirement could not be found VersionConflict The requested version of a project conflicts with an already activated version of the same project UnknownExtra One of the extras requested was not recognized by the distribution it was requested from ExtractionError A problem occurred extracting a resource to the Python Egg cache The following attributes are available on instances of this exception manager The resource manager that raised this exception cache path The base directory for resource extraction original error The exception instance that caused extraction to fail Supporting Custom Importers By default pkg resources supports normal filesystem imports and zipimport importers If you wish to use the pkg resources features with other PEP 302 compatible importers or module loaders you may need to register various handlers and support functions using these APIs register finder importer type distribution finder 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 when passed a path item the importer instance and an only flag yields Distribution instances found under that path item The only flag if true means the finder should yield only Distribution objects whose location is equal to the path item provided See the source of the pkg resources find on path function for an example finder function register loader type loader type provider factory Register provider factory to make IResourceProvider objects for loader type loader type is the type or class of a PEP 302 module loader and provider factory is a function that when passed a module object returns an IResourceProvider for that module allowing it to be used with the ResourceManager API register namespace handler importer type namespace handler Register namespace handler to declare namespace packages for the given importer type importer type is the type or class of a PEP 302 importer sys path item handler and namespace handler is a callable with a signature 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 relevant importer object has already agreed that it can handle the relevant path item The handler should only return a subpath if the module path does not already contain an equivalent subpath Otherwise it should return None For an example namespace handler see the source of the pkg resources file ns

    Original URL path: http://peak.telecommunity.com/DevCenter/PkgResources?action=subscribe (2016-04-24)
    Open archived version from archive


  • initialization are added This method is a shortcut for using the find distributions function to find the distributions from each item in search path and then calling add to add each one to the environment Requirement Objects Requirement objects express what versions of a project are suitable for some purpose These objects or their string form are used by various pkg resources APIs in order to find distributions that a script or distribution needs Requirements Parsing parse requirements s Yield Requirement objects for a string or iterable of lines Each requirement must start on a new line See below for syntax Requirement parse s Create a Requirement object from a string or iterable of lines A ValueError is raised if the string or lines do not contain a valid requirement specifier or if they contain more than one specifier To parse multiple specifiers from a string or iterable of strings use parse requirements instead The syntax of a requirement specifier can be defined in EBNF as follows requirement project name versionspec extras versionspec comparison version comparison version comparison extras extralist extralist identifier identifier project name identifier identifier A Za z0 9 version A Za z0 9 Tokens can be separated by whitespace and a requirement can be continued over multiple lines using a backslash Line end comments using are also allowed Some examples of valid requirement specifiers FooProject 1 2 Fizzy foo bar PickyThing 1 6 1 9 1 9 6 2 0a0 2 4c1 SomethingWhoseVersionIDontCareAbout The project name is the only required portion of a requirement string and if it s the only thing supplied the requirement will accept any version of that project The extras in a requirement are used to request optional features of a project that may require additional project distributions in order to function For example if the hypothetical Report O Rama project offered optional PDF support it might require an additional library in order to provide that support Thus a project needing Report O Rama s PDF features could use a requirement of Report O Rama PDF to request installation or activation of both Report O Rama and any libraries it needs in order to provide PDF support For example you could use easy install py Report O Rama PDF To install the necessary packages using the EasyInstall program or call pkg resources require Report O Rama PDF to add the necessary distributions to sys path at runtime Requirement Methods and Attributes contains dist or version Return true if dist or version fits the criteria for this requirement If dist or version is a Distribution object its project name must match the requirement s project name and its version must meet the requirement s version criteria If dist or version is a string it is parsed using the parse version utility function Otherwise it is assumed to be an already parsed version The Requirement object s version specifiers specs are internally sorted into ascending version order and used to establish what ranges of versions are acceptable Adjacent redundant conditions are effectively consolidated e g 1 2 produces the same results as 1 and 2 3 produces the same results as 3 versions are excised from the ranges they fall within The version being tested for acceptability is then checked for membership in the resulting ranges Note that providing conflicting conditions for the same version e g 2 2 or 2 2 is meaningless and may therefore produce bizarre results when compared with actual version number s eq other requirement A requirement compares equal to another requirement if they have case insensitively equal project names version specifiers and extras The order that extras and version specifiers are in is also ignored Equal requirements also have equal hashes so that requirements can be used in sets or as dictionary keys str The string form of a Requirement is a string that if passed to Requirement parse would return an equal Requirement object project name The name of the required project key An all lowercase version of the project name useful for comparison or indexing extras A tuple of names of extras that this requirement calls for These will be all lowercase and normalized using the safe extra parsing utility function so they may not exactly equal the extras the requirement was created with specs A list of op version tuples sorted in ascending parsed version order The op in each tuple is a comparison operator represented as a string The version is the unparsed version number The relative order of tuples containing the same version numbers is undefined since having more than one operator for a given version is either redundant or self contradictory Entry Points Entry points are a simple way for distributions to advertise Python objects such as functions or classes for use by other distributions Extensible applications and frameworks can search for entry points with a particular name or group either from a specific distribution or from all active distributions on sys path and then inspect or load the advertised objects at will Entry points belong to groups which are named with a dotted name similar to a Python package or module name For example the setuptools package uses an entry point named distutils commands in order to find commands defined by distutils extensions setuptools treats the names of entry points defined in that group as the acceptable commands for a setup script In a similar way other packages can define their own entry point groups either using dynamic names within the group like distutils commands or possibly using predefined names within the group For example a blogging framework that offers various pre or post publishing hooks might define an entry point group and look for entry points named pre process and post process within that group To advertise an entry point a project needs to use setuptools and provide an entry points argument to setup in its setup script so that the entry points will be included in the distribution s metadata For more details see the setuptools documentation XXX link here to setuptools Each project distribution can advertise at most one entry point of a given name within the same entry point group For example a distutils extension could advertise two different distutils commands entry points as long as they had different names However there is nothing that prevents different projects from advertising entry points of the same name in the same group In some cases this is a desirable thing since the application or framework that uses the entry points may be calling them as hooks or in some other way combining them It is up to the application or framework to decide what to do if multiple distributions advertise an entry point some possibilities include using both entry points displaying an error message using the first one found in sys path order etc Convenience API In the following functions the dist argument can be a Distribution instance a Requirement instance or a string specifying a requirement i e project name version etc If the argument is a string or Requirement the specified distribution is located and added to sys path if not already present An error will be raised if a matching distribution is not available The group argument should be a string containing a dotted identifier identifying an entry point group If you are defining an entry point group you should include some portion of your package s name in the group name so as to avoid collision with other packages entry point groups load entry point dist group name Load the named entry point from the specified distribution or raise ImportError get entry info dist group name Return an EntryPoint object for the given group and name from the specified distribution Returns None if the distribution has not advertised a matching entry point get entry map dist group None Return the distribution s entry point map for group or the full entry map for the distribution This function always returns a dictionary even if the distribution advertises no entry points If group is given the dictionary maps entry point names to the corresponding EntryPoint object If group is None the dictionary maps group names to dictionaries that then map entry point names to the corresponding EntryPoint instance in that group iter entry points group name None 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 on sys path otherwise only ones matching both group and name are yielded Entry points are yielded from the active distributions in the order that the distributions appear on sys path Within entry points for a particular distribution however there is no particular ordering This API is actually a method of the global working set object see the section above on Basic WorkingSet Methods for more information Creating and Parsing EntryPoint name module name attrs extras dist None Create an EntryPoint instance name is the entry point name The module name is the dotted name of the module containing the advertised object attrs is an optional tuple of names to look up from the module to obtain the advertised object For example an attrs of foo bar and a module name of baz would mean that the advertised object could be obtained by the following code import baz advertised object baz foo bar The extras are an optional tuple of extra feature names that the distribution needs in order to provide this entry point When the entry point is loaded these extra features are looked up in the dist argument to find out what other distributions may need to be activated on sys path see the load method for more details The extras argument is only meaningful if dist is specified dist must be a Distribution instance EntryPoint parse src dist None classmethod 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 as is the whitespace shown between some of the items The dist argument is passed through to the EntryPoint constructor along with the other values parsed from src EntryPoint parse group group lines dist None classmethod Parse lines a string or sequence of lines to create a dictionary mapping entry point names to EntryPoint objects ValueError is raised if entry point names are duplicated if group is not a valid entry point group name or if there are any syntax errors Note the group parameter is used only for validation and to create more informative error messages If dist is provided it will be used to set the dist attribute of the created EntryPoint objects EntryPoint parse map data dist None classmethod Parse data into a dictionary mapping group names to dictionaries mapping entry point names to EntryPoint objects If data is a dictionary then the keys are used as group names and the values are passed to parse group as the lines argument If data is a string or sequence of lines it is first split into ini style sections using the split sections utility function and the section names are used as group names In either case the dist argument is passed through to parse group so that the entry points will be linked to the specified distribution EntryPoint Objects For simple introspection EntryPoint objects have attributes that correspond exactly to the constructor argument names name module name attrs extras and dist are all available In addition the following methods are provided load require True env None installer None Load the entry point returning the advertised Python object or raise ImportError if it cannot be obtained If require is a true value then require env installer is called before attempting the import require env None installer None Ensure that any extras needed by the entry point are available on sys path UnknownExtra is raised if the EntryPoint has extras but no dist or if the named extras are not defined by the distribution If env is supplied it must be an Environment and it will be used to search for needed distributions if they are not already present on sys path If installer is supplied it must be a callable taking a Requirement instance and returning a matching importable Distribution instance or None str The string form of an EntryPoint is a string that could be passed to EntryPoint parse to produce an equivalent EntryPoint Distribution Objects Distribution objects represent collections of Python code that may or may not be importable and may or may not have metadata and resources associated with them Their metadata may include information such as what other projects the distribution depends on what entry points the distribution advertises and so on Getting or Creating Distributions Most commonly you ll obtain Distribution objects from a WorkingSet or an Environment See the sections above on WorkingSet Objects and Environment Objects which are containers for active distributions and available distributions respectively You can also obtain Distribution objects from one of these high level APIs find distributions path item only False Yield distributions accessible via path item If only is true yield only distributions whose location is equal to path item In other words if only is true this yields any distributions that would be importable if path item were on sys path If only is false this also yields distributions that are in or under path item but would not be importable unless their locations were also added to sys path get distribution dist spec Return a Distribution object for a given Requirement or string If dist spec is already a Distribution instance it is returned If it is a Requirement object or a string that can be parsed into one it is used to locate and activate a matching distribution which is then returned However if you re creating specialized tools for working with distributions or creating a new distribution format you may also need to create Distribution objects directly using one of the three constructors below These constructors all take an optional metadata argument which is used to access any resources or metadata associated with the distribution metadata must be an object that implements the IResourceProvider interface or None If it is None an EmptyProvider is used instead Distribution objects implement both the IResourceProvider and IMetadataProvider Methods by delegating them to the metadata object Distribution from location location basename metadata None kw classmethod Create a distribution for location which must be a string such as a URL filename or other string that might be used on sys path basename is a string naming the distribution like Foo 1 2 py2 4 egg If basename ends with egg then the project s name version python version and platform are extracted from the filename and used to set those properties of the created distribution Any additional keyword arguments are forwarded to the Distribution constructor Distribution from filename filename metadata None kw classmethod Create a distribution by parsing a local filename This is a shorter way of saying Distribution from location normalize path filename os path basename filename metadata In other words it creates a distribution whose location is the normalize form of the filename parsing name and version information from the base portion of the filename Any additional keyword arguments are forwarded to the Distribution constructor Distribution location metadata project name version py version platform precedence Create a distribution by setting its properties All arguments are optional and default to None except for py version which defaults to the current Python version and precedence which defaults to EGG DIST for more details see precedence under Distribution Attributes below Note that it s usually easier to use the from filename or from location constructors than to specify all these arguments individually Distribution Attributes location A string indicating the distribution s location For an importable distribution this is the string that would be added to sys path to make it actively importable For non importable distributions this is simply a filename URL or other way of locating the distribution project name A string naming the project that this distribution is for Project names are defined by a project s setup script and they are used to identify projects on PyPI When a Distribution is constructed the project name argument is passed through the safe name utility function to filter out any unacceptable characters key dist key is short for dist project name lower It s used for case insensitive comparison and indexing of distributions by project name extras A list of strings giving the names of extra features defined by the project s dependency list the extras require argument specified in the project s setup script version A string denoting what release of the project this distribution contains When a Distribution is constructed the version argument is passed through the safe version utility function to filter out any unacceptable characters If no version is specified at construction time then attempting to access this attribute later will cause the Distribution to try to discover its version by reading its PKG INFO metadata file If PKG INFO is unavailable or can t be parsed ValueError is raised parsed version The parsed version is a tuple representing a parsed form of the distribution s version dist parsed version is a shortcut for calling parse version dist version It is used to compare or sort distributions by version See the Parsing Utilities section below for more information on the parse version function Note that accessing parsed version may result in a ValueError if the Distribution was constructed without a version and without metadata capable of supplying the missing version info py version The major minor Python version the distribution supports as a string For example 2 3 or 2 4 The default is the current version of Python platform A string representing the platform the distribution is intended for or None if the distribution is pure Python and therefore cross platform See Platform Utilities below for more information on platform strings precedence A distribution s precedence is used to determine the relative order of two distributions that have the same project name and parsed version The default precedence is pkg resources EGG DIST which is the highest i e most preferred precedence The full list of predefined precedences from most preferred to least preferred is EGG DIST BINARY DIST SOURCE DIST CHECKOUT DIST and DEVELOP DIST Normally precedences other than EGG DIST are used only by the setuptools package index module when sorting distributions found in a package index to determine their suitability for installation System and Development eggs i e ones that use the egg info format however are automatically given a precedence of DEVELOP DIST Distribution Methods activate path None Ensure distribution is importable on path If path is None sys path is used instead This ensures that the distribution s location is in the path list and it also performs any necessary namespace package fixups or declarations That is if the distribution contains namespace packages this method ensures that they are declared and that the distribution s contents for those namespace packages are merged with the contents provided by any other active distributions See the section above on Namespace Package Support for more information pkg resources adds a notification callback to the global working set that ensures this method is called whenever a distribution is added to it Therefore you should not normally need to explicitly call this method Note that this means that namespace packages on sys path are always imported as soon as pkg resources is which is another reason why namespace packages should not contain any code or import statements as requirement Return a Requirement instance that matches this distribution s project name and version requires extras List the Requirement objects that specify this distribution s dependencies If extras is specified it should be a sequence of names of extras defined by the distribution and the list returned will then include any dependencies needed to support the named extras clone kw Create a copy of the distribution Any supplied keyword arguments override the corresponding argument to the Distribution constructor allowing you to change some of the copied distribution s attributes egg name Return what this distribution s standard filename should be not including the egg extension For example a distribution for project Foo version 1 2 that runs on Python 2 3 for Windows would have an egg name of Foo 1 2 py2 3 win32 Any dashes in the name or version are converted to underscores Distribution from location will convert them back when parsing a egg file name cmp other hash Distribution objects are hashed and compared on the basis of their parsed version and precedence followed by their key lowercase project name location Python version and platform The following methods are used to access EntryPoint objects advertised by the distribution See the section above on Entry Points for more detailed information about these operations get entry info group name Return the EntryPoint object for group and name or None if no such point is advertised by this distribution get entry map group None Return the entry point map for group If group is None return a dictionary mapping group names to entry point maps for all groups An entry point map is a dictionary of entry point names to EntryPoint objects load entry point group name Short for get entry info group name load Returns the object advertised by the named entry point or raises ImportError if the entry point isn t advertised by this distribution or there is some other import problem In addition to the above methods Distribution objects also implement all of the IResourceProvider and IMetadataProvider Methods which are documented in later sections has metadata name metadata isdir name metadata listdir name get metadata name get metadata lines name run script script name namespace get resource filename manager resource name get resource stream manager resource name get resource string manager resource name has resource resource name resource isdir resource name resource listdir resource name If the distribution was created with a metadata argument these resource and metadata access methods are all delegated to that metadata provider Otherwise they are delegated to an EmptyProvider so that the distribution will appear to have no resources or metadata This delegation approach is used so that supporting custom importers or new distribution formats can be done simply by creating an appropriate IResourceProvider implementation see the section below on Supporting Custom Importers for more details ResourceManager API The ResourceManager class provides uniform access to package resources whether those resources exist as files and directories or are compressed in an archive of some kind Normally you do not need to create or explicitly manage ResourceManager instances as the pkg resources module creates a global instance for you and makes most of its methods available as top level names in the pkg resources module namespace So for example this code actually calls the resource string method of the global ResourceManager import pkg resources my data pkg resources resource string name foo dat Thus you can use the APIs below without needing an explicit ResourceManager instance just import and use them as needed Basic Resource Access In the following methods the package or requirement argument may be either a Python package module name e g foo bar or a Requirement instance If it is a package or module name the named module or package must be importable i e be in a distribution or directory on sys path and the resource name argument is interpreted relative to the named package Note that if a module name is used then the resource name is relative to the package immediately containing the named module Also you should not use use a namespace package name because a namespace package can be spread across multiple distributions and is therefore ambiguous as to which distribution should be searched for the resource If it is a Requirement then the requirement is automatically resolved searching the current Environment if necessary and a matching distribution is added to the WorkingSet and sys path if one was not already present Unless the Requirement can t be satisfied in which case an exception is raised The resource name argument is then interpreted relative to the root of the identified distribution i e its first path segment will be treated as a peer of the top level modules or packages in the distribution Note that resource names must be separated paths and cannot be absolute i e no leading or contain relative names like Do not use os path routines to manipulate resource paths as they are not filesystem paths resource exists package or requirement resource name Does the named resource exist Return True or False accordingly resource stream package or requirement resource name Return a readable file like object for the specified resource it may be an actual file a StringIO or some similar object The stream is in binary mode in the sense that whatever bytes are in the resource will be read as is resource string package or requirement resource name Return the specified resource as a string The resource is read in binary fashion such that the returned string contains exactly the bytes that are stored in the resource resource isdir package or requirement resource name Is the named resource a directory Return True or False accordingly resource listdir package or requirement resource name List the contents of the named resource directory just like os listdir except that it works even if the resource is in a zipfile Note that only resource exists and resource isdir are insensitive as to the resource type You cannot use resource listdir on a file resource and you can t use resource string or resource stream on directory resources Using an inappropriate method for the resource type may result in an exception or undefined behavior depending on the platform and distribution format involved Resource Extraction resource filename package or requirement resource name Sometimes it is not sufficient to access a resource in string or stream form and a true filesystem filename is needed In such cases you can use this method or module level function to obtain a filename for a resource If the resource is in an archive distribution such as a zipped egg it will be extracted to a cache directory and the filename within the cache will be returned If the named resource is a directory then all resources within that directory including subdirectories are also extracted If the named resource is a C extension or eager resource see the setuptools documentation for details then all C extensions and eager resources are extracted at the same time Archived resources are extracted to a cache location that can be managed by the following two methods set extraction path path 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 resource provider 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 On Windows for example you can t unlink pyd or dll files that are still in use Note that you may not change the extraction path for a given resource manager once resources have been extracted unless you first call cleanup resources cleanup resources force False 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 Provider Interface If you are implementing an IResourceProvider and or IMetadataProvider for a new distribution archive format you may need to use the following IResourceManager methods to co ordinate extraction of resources to the filesystem If you re not implementing an archive format however you have no need to use these methods Unlike the other methods listed above they are not available as top level functions tied to the global ResourceManager you must therefore have an explicit ResourceManager instance to use them get cache path archive name names 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 extraction error Raise an ExtractionError describing the active exception as interfering with the extraction process You should call this if you encounter any OS errors extracting the file to the cache path it will format the operating system exception for you and add other information to the ExtractionError instance that may be needed by programs that want to wrap or handle extraction errors themselves postprocess tempname filename Perform any platform specific postprocessing of tempname 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 Metadata API The metadata API is used to access metadata resources bundled in a pluggable distribution Metadata resources are virtual files or directories containing information about the distribution such as might be used by an extensible application or framework to connect plugins Like other kinds of resources metadata resource names are separated and should not contain or begin with a You should not use os path routines to manipulate resource paths The metadata API is provided by objects implementing the IMetadataProvider or IResourceProvider interfaces Distribution objects implement this interface as do objects returned by the get provider function get provider package or requirement If a package name is supplied return an IResourceProvider for the package If a Requirement is supplied resolve it by returning a Distribution from the current working set searching the current Environment if necessary and adding the newly found Distribution to the working set If the named package can t be imported or the Requirement can t be satisfied an exception is raised NOTE if you use a package name rather than a Requirement the object you get back may not be a pluggable distribution depending on the method by which the package was installed In particular development packages and single version externally managed packages do not have any way to map from a package name to the corresponding project s metadata Do not write code that passes a package name to get provider and then tries to retrieve project metadata from the returned object It may appear to work when the named package is in an egg file or directory but it will fail in other installation scenarios If you want project metadata you need to ask for a project not a package IMetadataProvider Methods The methods provided by objects such as Distribution instances that implement the IMetadataProvider or IResourceProvider interfaces are has metadata name Does the named metadata resource exist metadata isdir name Is the named metadata resource a directory metadata listdir name List of metadata names in the directory like os listdir get metadata name Return the named metadata resource as a string The data is read in binary mode i e the exact bytes of the resource file are returned get metadata lines name Yield named metadata resource as list of non blank non comment lines This is short for calling yield lines provider get metadata name See the section on yield lines below for more information on the syntax it recognizes run script script name namespace Execute the named script in the supplied namespace dictionary Raises ResolutionError if there is no script by that name in the scripts metadata directory namespace should be a Python dictionary usually a module dictionary if the script is being run as a module Exceptions pkg resources provides a simple exception hierarchy for problems that may occur when processing requests to locate and activate packages ResolutionError DistributionNotFound VersionConflict UnknownExtra ExtractionError ResolutionError This class is used as a base class for the other three exceptions so that you can catch all of them with a single except clause It is also raised directly for miscellaneous requirement resolution problems like trying to run a script that doesn t exist in the distribution it was requested from DistributionNotFound A distribution needed to fulfill a requirement could not be found VersionConflict The requested version of a project conflicts with an already activated version of the same project UnknownExtra One of the extras requested was not recognized by the distribution it was requested from ExtractionError A problem occurred extracting a resource to the Python Egg cache The following attributes are available on instances of this exception manager The resource manager that raised this exception cache path The base directory for resource extraction original error The exception instance that caused extraction to fail Supporting Custom Importers By default pkg resources supports normal filesystem imports and zipimport importers If you wish to use the pkg resources features with other PEP 302 compatible importers or module loaders you may need to register various handlers and support functions using these APIs register finder importer type distribution finder 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 when passed a path item the importer instance and an only flag yields Distribution instances found under that path item The only flag if true means the finder should yield only Distribution objects whose location is equal to the path item provided See the source of the pkg resources find on path function for an example finder function register loader type loader type provider factory Register provider factory to make IResourceProvider objects for loader type loader type is the type or class of a PEP 302 module loader and provider factory is a function that when passed a module object returns an IResourceProvider for that module allowing it to be used with the ResourceManager API register namespace handler importer type namespace handler Register namespace handler to declare namespace packages for the given importer type importer type is the type or class of a PEP 302 importer sys path item handler and namespace handler is a callable with a signature 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 relevant importer object has already agreed that it can handle the relevant path item The handler should only return a subpath if the module path does not already contain an equivalent subpath Otherwise it should return None For an example namespace handler see the source of the pkg resources file ns

    Original URL path: http://peak.telecommunity.com/DevCenter/PkgResources?action=format&mimetype=text/xml (2016-04-24)
    Open archived version from archive

  • Attachments for "PkgResources" - The PEAK Developers' Center
    FrontPage RecentChanges TitleIndex WordIndex SiteNavigation HelpContents Attached Files No attachments stored for PkgResources You are not allowed to upload files ShowText of this page EditText of this page FindPage by browsing title search text search or an index Or try

    Original URL path: http://peak.telecommunity.com/DevCenter/PkgResources?action=AttachFile (2016-04-24)
    Open archived version from archive

  • PkgResources - The PEAK Developers' Center
    is a shortcut for using the find distributions function to find the distributions from each item in search path and then calling add to add each one to the environment Requirement Objects Requirement objects express what versions of a project are suitable for some purpose These objects or their string form are used by various pkg resources APIs in order to find distributions that a script or distribution needs Requirements Parsing parse requirements s Yield Requirement objects for a string or iterable of lines Each requirement must start on a new line See below for syntax Requirement parse s Create a Requirement object from a string or iterable of lines A ValueError is raised if the string or lines do not contain a valid requirement specifier or if they contain more than one specifier To parse multiple specifiers from a string or iterable of strings use parse requirements instead The syntax of a requirement specifier can be defined in EBNF as follows requirement project name versionspec extras versionspec comparison version comparison version comparison extras extralist extralist identifier identifier project name identifier identifier A Za z0 9 version A Za z0 9 Tokens can be separated by whitespace and a requirement can be continued over multiple lines using a backslash Line end comments using are also allowed Some examples of valid requirement specifiers FooProject 1 2 Fizzy foo bar PickyThing 1 6 1 9 1 9 6 2 0a0 2 4c1 SomethingWhoseVersionIDontCareAbout The project name is the only required portion of a requirement string and if it s the only thing supplied the requirement will accept any version of that project The extras in a requirement are used to request optional features of a project that may require additional project distributions in order to function For example if the hypothetical Report O Rama project offered optional PDF support it might require an additional library in order to provide that support Thus a project needing Report O Rama s PDF features could use a requirement of Report O Rama PDF to request installation or activation of both Report O Rama and any libraries it needs in order to provide PDF support For example you could use easy install py Report O Rama PDF To install the necessary packages using the EasyInstall program or call pkg resources require Report O Rama PDF to add the necessary distributions to sys path at runtime Requirement Methods and Attributes contains dist or version Return true if dist or version fits the criteria for this requirement If dist or version is a Distribution object its project name must match the requirement s project name and its version must meet the requirement s version criteria If dist or version is a string it is parsed using the parse version utility function Otherwise it is assumed to be an already parsed version The Requirement object s version specifiers specs are internally sorted into ascending version order and used to establish what ranges of versions are acceptable Adjacent redundant conditions are effectively consolidated e g 1 2 produces the same results as 1 and 2 3 produces the same results as 3 versions are excised from the ranges they fall within The version being tested for acceptability is then checked for membership in the resulting ranges Note that providing conflicting conditions for the same version e g 2 2 or 2 2 is meaningless and may therefore produce bizarre results when compared with actual version number s eq other requirement A requirement compares equal to another requirement if they have case insensitively equal project names version specifiers and extras The order that extras and version specifiers are in is also ignored Equal requirements also have equal hashes so that requirements can be used in sets or as dictionary keys str The string form of a Requirement is a string that if passed to Requirement parse would return an equal Requirement object project name The name of the required project key An all lowercase version of the project name useful for comparison or indexing extras A tuple of names of extras that this requirement calls for These will be all lowercase and normalized using the safe extra parsing utility function so they may not exactly equal the extras the requirement was created with specs A list of op version tuples sorted in ascending parsed version order The op in each tuple is a comparison operator represented as a string The version is the unparsed version number The relative order of tuples containing the same version numbers is undefined since having more than one operator for a given version is either redundant or self contradictory Entry Points Entry points are a simple way for distributions to advertise Python objects such as functions or classes for use by other distributions Extensible applications and frameworks can search for entry points with a particular name or group either from a specific distribution or from all active distributions on sys path and then inspect or load the advertised objects at will Entry points belong to groups which are named with a dotted name similar to a Python package or module name For example the setuptools package uses an entry point named distutils commands in order to find commands defined by distutils extensions setuptools treats the names of entry points defined in that group as the acceptable commands for a setup script In a similar way other packages can define their own entry point groups either using dynamic names within the group like distutils commands or possibly using predefined names within the group For example a blogging framework that offers various pre or post publishing hooks might define an entry point group and look for entry points named pre process and post process within that group To advertise an entry point a project needs to use setuptools and provide an entry points argument to setup in its setup script so that the entry points will be included in the distribution s metadata For more details see the setuptools documentation XXX link here to setuptools Each project distribution can advertise at most one entry point of a given name within the same entry point group For example a distutils extension could advertise two different distutils commands entry points as long as they had different names However there is nothing that prevents different projects from advertising entry points of the same name in the same group In some cases this is a desirable thing since the application or framework that uses the entry points may be calling them as hooks or in some other way combining them It is up to the application or framework to decide what to do if multiple distributions advertise an entry point some possibilities include using both entry points displaying an error message using the first one found in sys path order etc Convenience API In the following functions the dist argument can be a Distribution instance a Requirement instance or a string specifying a requirement i e project name version etc If the argument is a string or Requirement the specified distribution is located and added to sys path if not already present An error will be raised if a matching distribution is not available The group argument should be a string containing a dotted identifier identifying an entry point group If you are defining an entry point group you should include some portion of your package s name in the group name so as to avoid collision with other packages entry point groups load entry point dist group name Load the named entry point from the specified distribution or raise ImportError get entry info dist group name Return an EntryPoint object for the given group and name from the specified distribution Returns None if the distribution has not advertised a matching entry point get entry map dist group None Return the distribution s entry point map for group or the full entry map for the distribution This function always returns a dictionary even if the distribution advertises no entry points If group is given the dictionary maps entry point names to the corresponding EntryPoint object If group is None the dictionary maps group names to dictionaries that then map entry point names to the corresponding EntryPoint instance in that group iter entry points group name None 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 on sys path otherwise only ones matching both group and name are yielded Entry points are yielded from the active distributions in the order that the distributions appear on sys path Within entry points for a particular distribution however there is no particular ordering This API is actually a method of the global working set object see the section above on Basic WorkingSet Methods for more information Creating and Parsing EntryPoint name module name attrs extras dist None Create an EntryPoint instance name is the entry point name The module name is the dotted name of the module containing the advertised object attrs is an optional tuple of names to look up from the module to obtain the advertised object For example an attrs of foo bar and a module name of baz would mean that the advertised object could be obtained by the following code import baz advertised object baz foo bar The extras are an optional tuple of extra feature names that the distribution needs in order to provide this entry point When the entry point is loaded these extra features are looked up in the dist argument to find out what other distributions may need to be activated on sys path see the load method for more details The extras argument is only meaningful if dist is specified dist must be a Distribution instance EntryPoint parse src dist None classmethod 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 as is the whitespace shown between some of the items The dist argument is passed through to the EntryPoint constructor along with the other values parsed from src EntryPoint parse group group lines dist None classmethod Parse lines a string or sequence of lines to create a dictionary mapping entry point names to EntryPoint objects ValueError is raised if entry point names are duplicated if group is not a valid entry point group name or if there are any syntax errors Note the group parameter is used only for validation and to create more informative error messages If dist is provided it will be used to set the dist attribute of the created EntryPoint objects EntryPoint parse map data dist None classmethod Parse data into a dictionary mapping group names to dictionaries mapping entry point names to EntryPoint objects If data is a dictionary then the keys are used as group names and the values are passed to parse group as the lines argument If data is a string or sequence of lines it is first split into ini style sections using the split sections utility function and the section names are used as group names In either case the dist argument is passed through to parse group so that the entry points will be linked to the specified distribution EntryPoint Objects For simple introspection EntryPoint objects have attributes that correspond exactly to the constructor argument names name module name attrs extras and dist are all available In addition the following methods are provided load require True env None installer None Load the entry point returning the advertised Python object or raise ImportError if it cannot be obtained If require is a true value then require env installer is called before attempting the import require env None installer None Ensure that any extras needed by the entry point are available on sys path UnknownExtra is raised if the EntryPoint has extras but no dist or if the named extras are not defined by the distribution If env is supplied it must be an Environment and it will be used to search for needed distributions if they are not already present on sys path If installer is supplied it must be a callable taking a Requirement instance and returning a matching importable Distribution instance or None str The string form of an EntryPoint is a string that could be passed to EntryPoint parse to produce an equivalent EntryPoint Distribution Objects Distribution objects represent collections of Python code that may or may not be importable and may or may not have metadata and resources associated with them Their metadata may include information such as what other projects the distribution depends on what entry points the distribution advertises and so on Getting or Creating Distributions Most commonly you ll obtain Distribution objects from a WorkingSet or an Environment See the sections above on WorkingSet Objects and Environment Objects which are containers for active distributions and available distributions respectively You can also obtain Distribution objects from one of these high level APIs find distributions path item only False Yield distributions accessible via path item If only is true yield only distributions whose location is equal to path item In other words if only is true this yields any distributions that would be importable if path item were on sys path If only is false this also yields distributions that are in or under path item but would not be importable unless their locations were also added to sys path get distribution dist spec Return a Distribution object for a given Requirement or string If dist spec is already a Distribution instance it is returned If it is a Requirement object or a string that can be parsed into one it is used to locate and activate a matching distribution which is then returned However if you re creating specialized tools for working with distributions or creating a new distribution format you may also need to create Distribution objects directly using one of the three constructors below These constructors all take an optional metadata argument which is used to access any resources or metadata associated with the distribution metadata must be an object that implements the IResourceProvider interface or None If it is None an EmptyProvider is used instead Distribution objects implement both the IResourceProvider and IMetadataProvider Methods by delegating them to the metadata object Distribution from location location basename metadata None kw classmethod Create a distribution for location which must be a string such as a URL filename or other string that might be used on sys path basename is a string naming the distribution like Foo 1 2 py2 4 egg If basename ends with egg then the project s name version python version and platform are extracted from the filename and used to set those properties of the created distribution Any additional keyword arguments are forwarded to the Distribution constructor Distribution from filename filename metadata None kw classmethod Create a distribution by parsing a local filename This is a shorter way of saying Distribution from location normalize path filename os path basename filename metadata In other words it creates a distribution whose location is the normalize form of the filename parsing name and version information from the base portion of the filename Any additional keyword arguments are forwarded to the Distribution constructor Distribution location metadata project name version py version platform precedence Create a distribution by setting its properties All arguments are optional and default to None except for py version which defaults to the current Python version and precedence which defaults to EGG DIST for more details see precedence under Distribution Attributes below Note that it s usually easier to use the from filename or from location constructors than to specify all these arguments individually Distribution Attributes location A string indicating the distribution s location For an importable distribution this is the string that would be added to sys path to make it actively importable For non importable distributions this is simply a filename URL or other way of locating the distribution project name A string naming the project that this distribution is for Project names are defined by a project s setup script and they are used to identify projects on PyPI When a Distribution is constructed the project name argument is passed through the safe name utility function to filter out any unacceptable characters key dist key is short for dist project name lower It s used for case insensitive comparison and indexing of distributions by project name extras A list of strings giving the names of extra features defined by the project s dependency list the extras require argument specified in the project s setup script version A string denoting what release of the project this distribution contains When a Distribution is constructed the version argument is passed through the safe version utility function to filter out any unacceptable characters If no version is specified at construction time then attempting to access this attribute later will cause the Distribution to try to discover its version by reading its PKG INFO metadata file If PKG INFO is unavailable or can t be parsed ValueError is raised parsed version The parsed version is a tuple representing a parsed form of the distribution s version dist parsed version is a shortcut for calling parse version dist version It is used to compare or sort distributions by version See the Parsing Utilities section below for more information on the parse version function Note that accessing parsed version may result in a ValueError if the Distribution was constructed without a version and without metadata capable of supplying the missing version info py version The major minor Python version the distribution supports as a string For example 2 3 or 2 4 The default is the current version of Python platform A string representing the platform the distribution is intended for or None if the distribution is pure Python and therefore cross platform See Platform Utilities below for more information on platform strings precedence A distribution s precedence is used to determine the relative order of two distributions that have the same project name and parsed version The default precedence is pkg resources EGG DIST which is the highest i e most preferred precedence The full list of predefined precedences from most preferred to least preferred is EGG DIST BINARY DIST SOURCE DIST CHECKOUT DIST and DEVELOP DIST Normally precedences other than EGG DIST are used only by the setuptools package index module when sorting distributions found in a package index to determine their suitability for installation System and Development eggs i e ones that use the egg info format however are automatically given a precedence of DEVELOP DIST Distribution Methods activate path None Ensure distribution is importable on path If path is None sys path is used instead This ensures that the distribution s location is in the path list and it also performs any necessary namespace package fixups or declarations That is if the distribution contains namespace packages this method ensures that they are declared and that the distribution s contents for those namespace packages are merged with the contents provided by any other active distributions See the section above on Namespace Package Support for more information pkg resources adds a notification callback to the global working set that ensures this method is called whenever a distribution is added to it Therefore you should not normally need to explicitly call this method Note that this means that namespace packages on sys path are always imported as soon as pkg resources is which is another reason why namespace packages should not contain any code or import statements as requirement Return a Requirement instance that matches this distribution s project name and version requires extras List the Requirement objects that specify this distribution s dependencies If extras is specified it should be a sequence of names of extras defined by the distribution and the list returned will then include any dependencies needed to support the named extras clone kw Create a copy of the distribution Any supplied keyword arguments override the corresponding argument to the Distribution constructor allowing you to change some of the copied distribution s attributes egg name Return what this distribution s standard filename should be not including the egg extension For example a distribution for project Foo version 1 2 that runs on Python 2 3 for Windows would have an egg name of Foo 1 2 py2 3 win32 Any dashes in the name or version are converted to underscores Distribution from location will convert them back when parsing a egg file name cmp other hash Distribution objects are hashed and compared on the basis of their parsed version and precedence followed by their key lowercase project name location Python version and platform The following methods are used to access EntryPoint objects advertised by the distribution See the section above on Entry Points for more detailed information about these operations get entry info group name Return the EntryPoint object for group and name or None if no such point is advertised by this distribution get entry map group None Return the entry point map for group If group is None return a dictionary mapping group names to entry point maps for all groups An entry point map is a dictionary of entry point names to EntryPoint objects load entry point group name Short for get entry info group name load Returns the object advertised by the named entry point or raises ImportError if the entry point isn t advertised by this distribution or there is some other import problem In addition to the above methods Distribution objects also implement all of the IResourceProvider and IMetadataProvider Methods which are documented in later sections has metadata name metadata isdir name metadata listdir name get metadata name get metadata lines name run script script name namespace get resource filename manager resource name get resource stream manager resource name get resource string manager resource name has resource resource name resource isdir resource name resource listdir resource name If the distribution was created with a metadata argument these resource and metadata access methods are all delegated to that metadata provider Otherwise they are delegated to an EmptyProvider so that the distribution will appear to have no resources or metadata This delegation approach is used so that supporting custom importers or new distribution formats can be done simply by creating an appropriate IResourceProvider implementation see the section below on Supporting Custom Importers for more details ResourceManager API The ResourceManager class provides uniform access to package resources whether those resources exist as files and directories or are compressed in an archive of some kind Normally you do not need to create or explicitly manage ResourceManager instances as the pkg resources module creates a global instance for you and makes most of its methods available as top level names in the pkg resources module namespace So for example this code actually calls the resource string method of the global ResourceManager import pkg resources my data pkg resources resource string name foo dat Thus you can use the APIs below without needing an explicit ResourceManager instance just import and use them as needed Basic Resource Access In the following methods the package or requirement argument may be either a Python package module name e g foo bar or a Requirement instance If it is a package or module name the named module or package must be importable i e be in a distribution or directory on sys path and the resource name argument is interpreted relative to the named package Note that if a module name is used then the resource name is relative to the package immediately containing the named module Also you should not use use a namespace package name because a namespace package can be spread across multiple distributions and is therefore ambiguous as to which distribution should be searched for the resource If it is a Requirement then the requirement is automatically resolved searching the current Environment if necessary and a matching distribution is added to the WorkingSet and sys path if one was not already present Unless the Requirement can t be satisfied in which case an exception is raised The resource name argument is then interpreted relative to the root of the identified distribution i e its first path segment will be treated as a peer of the top level modules or packages in the distribution Note that resource names must be separated paths and cannot be absolute i e no leading or contain relative names like Do not use os path routines to manipulate resource paths as they are not filesystem paths resource exists package or requirement resource name Does the named resource exist Return True or False accordingly resource stream package or requirement resource name Return a readable file like object for the specified resource it may be an actual file a StringIO or some similar object The stream is in binary mode in the sense that whatever bytes are in the resource will be read as is resource string package or requirement resource name Return the specified resource as a string The resource is read in binary fashion such that the returned string contains exactly the bytes that are stored in the resource resource isdir package or requirement resource name Is the named resource a directory Return True or False accordingly resource listdir package or requirement resource name List the contents of the named resource directory just like os listdir except that it works even if the resource is in a zipfile Note that only resource exists and resource isdir are insensitive as to the resource type You cannot use resource listdir on a file resource and you can t use resource string or resource stream on directory resources Using an inappropriate method for the resource type may result in an exception or undefined behavior depending on the platform and distribution format involved Resource Extraction resource filename package or requirement resource name Sometimes it is not sufficient to access a resource in string or stream form and a true filesystem filename is needed In such cases you can use this method or module level function to obtain a filename for a resource If the resource is in an archive distribution such as a zipped egg it will be extracted to a cache directory and the filename within the cache will be returned If the named resource is a directory then all resources within that directory including subdirectories are also extracted If the named resource is a C extension or eager resource see the setuptools documentation for details then all C extensions and eager resources are extracted at the same time Archived resources are extracted to a cache location that can be managed by the following two methods set extraction path path 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 resource provider 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 On Windows for example you can t unlink pyd or dll files that are still in use Note that you may not change the extraction path for a given resource manager once resources have been extracted unless you first call cleanup resources cleanup resources force False 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 Provider Interface If you are implementing an IResourceProvider and or IMetadataProvider for a new distribution archive format you may need to use the following IResourceManager methods to co ordinate extraction of resources to the filesystem If you re not implementing an archive format however you have no need to use these methods Unlike the other methods listed above they are not available as top level functions tied to the global ResourceManager you must therefore have an explicit ResourceManager instance to use them get cache path archive name names 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 extraction error Raise an ExtractionError describing the active exception as interfering with the extraction process You should call this if you encounter any OS errors extracting the file to the cache path it will format the operating system exception for you and add other information to the ExtractionError instance that may be needed by programs that want to wrap or handle extraction errors themselves postprocess tempname filename Perform any platform specific postprocessing of tempname 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 Metadata API The metadata API is used to access metadata resources bundled in a pluggable distribution Metadata resources are virtual files or directories containing information about the distribution such as might be used by an extensible application or framework to connect plugins Like other kinds of resources metadata resource names are separated and should not contain or begin with a You should not use os path routines to manipulate resource paths The metadata API is provided by objects implementing the IMetadataProvider or IResourceProvider interfaces Distribution objects implement this interface as do objects returned by the get provider function get provider package or requirement If a package name is supplied return an IResourceProvider for the package If a Requirement is supplied resolve it by returning a Distribution from the current working set searching the current Environment if necessary and adding the newly found Distribution to the working set If the named package can t be imported or the Requirement can t be satisfied an exception is raised NOTE if you use a package name rather than a Requirement the object you get back may not be a pluggable distribution depending on the method by which the package was installed In particular development packages and single version externally managed packages do not have any way to map from a package name to the corresponding project s metadata Do not write code that passes a package name to get provider and then tries to retrieve project metadata from the returned object It may appear to work when the named package is in an egg file or directory but it will fail in other installation scenarios If you want project metadata you need to ask for a project not a package IMetadataProvider Methods The methods provided by objects such as Distribution instances that implement the IMetadataProvider or IResourceProvider interfaces are has metadata name Does the named metadata resource exist metadata isdir name Is the named metadata resource a directory metadata listdir name List of metadata names in the directory like os listdir get metadata name Return the named metadata resource as a string The data is read in binary mode i e the exact bytes of the resource file are returned get metadata lines name Yield named metadata resource as list of non blank non comment lines This is short for calling yield lines provider get metadata name See the section on yield lines below for more information on the syntax it recognizes run script script name namespace Execute the named script in the supplied namespace dictionary Raises ResolutionError if there is no script by that name in the scripts metadata directory namespace should be a Python dictionary usually a module dictionary if the script is being run as a module Exceptions pkg resources provides a simple exception hierarchy for problems that may occur when processing requests to locate and activate packages ResolutionError DistributionNotFound VersionConflict UnknownExtra ExtractionError ResolutionError This class is used as a base class for the other three exceptions so that you can catch all of them with a single except clause It is also raised directly for miscellaneous requirement resolution problems like trying to run a script that doesn t exist in the distribution it was requested from DistributionNotFound A distribution needed to fulfill a requirement could not be found VersionConflict The requested version of a project conflicts with an already activated version of the same project UnknownExtra One of the extras requested was not recognized by the distribution it was requested from ExtractionError A problem occurred extracting a resource to the Python Egg cache The following attributes are available on instances of this exception manager The resource manager that raised this exception cache path The base directory for resource extraction original error The exception instance that caused extraction to fail Supporting Custom Importers By default pkg resources supports normal filesystem imports and zipimport importers If you wish to use the pkg resources features with other PEP 302 compatible importers or module loaders you may need to register various handlers and support functions using these APIs register finder importer type distribution finder 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 when passed a path item the importer instance and an only flag yields Distribution instances found under that path item The only flag if true means the finder should yield only Distribution objects whose location is equal to the path item provided See the source of the pkg resources find on path function for an example finder function register loader type loader type provider factory Register provider factory to make IResourceProvider objects for loader type loader type is the type or class of a PEP 302 module loader and provider factory is a function that when passed a module object returns an IResourceProvider for that module allowing it to be used with the ResourceManager API register namespace handler importer type namespace handler Register namespace handler to declare namespace packages for the given importer type importer type is the type or class of a PEP 302 importer sys path item handler and namespace handler is a callable with a signature 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 relevant importer object has already agreed that it can handle the relevant path item The handler should only return a subpath if the module path does not already contain an equivalent subpath Otherwise it should return None For an example namespace handler see the source of the pkg resources file ns handler function which is used

    Original URL path: http://peak.telecommunity.com/DevCenter/PkgResources?action=DeletePage (2016-04-24)
    Open archived version from archive

  • PkgResources - The PEAK Developers' Center
    for using the find distributions function to find the distributions from each item in search path and then calling add to add each one to the environment Requirement Objects Requirement objects express what versions of a project are suitable for some purpose These objects or their string form are used by various pkg resources APIs in order to find distributions that a script or distribution needs Requirements Parsing parse requirements s Yield Requirement objects for a string or iterable of lines Each requirement must start on a new line See below for syntax Requirement parse s Create a Requirement object from a string or iterable of lines A ValueError is raised if the string or lines do not contain a valid requirement specifier or if they contain more than one specifier To parse multiple specifiers from a string or iterable of strings use parse requirements instead The syntax of a requirement specifier can be defined in EBNF as follows requirement project name versionspec extras versionspec comparison version comparison version comparison extras extralist extralist identifier identifier project name identifier identifier A Za z0 9 version A Za z0 9 Tokens can be separated by whitespace and a requirement can be continued over multiple lines using a backslash Line end comments using are also allowed Some examples of valid requirement specifiers FooProject 1 2 Fizzy foo bar PickyThing 1 6 1 9 1 9 6 2 0a0 2 4c1 SomethingWhoseVersionIDontCareAbout The project name is the only required portion of a requirement string and if it s the only thing supplied the requirement will accept any version of that project The extras in a requirement are used to request optional features of a project that may require additional project distributions in order to function For example if the hypothetical Report O Rama project offered optional PDF support it might require an additional library in order to provide that support Thus a project needing Report O Rama s PDF features could use a requirement of Report O Rama PDF to request installation or activation of both Report O Rama and any libraries it needs in order to provide PDF support For example you could use easy install py Report O Rama PDF To install the necessary packages using the EasyInstall program or call pkg resources require Report O Rama PDF to add the necessary distributions to sys path at runtime Requirement Methods and Attributes contains dist or version Return true if dist or version fits the criteria for this requirement If dist or version is a Distribution object its project name must match the requirement s project name and its version must meet the requirement s version criteria If dist or version is a string it is parsed using the parse version utility function Otherwise it is assumed to be an already parsed version The Requirement object s version specifiers specs are internally sorted into ascending version order and used to establish what ranges of versions are acceptable Adjacent redundant conditions are effectively consolidated e g 1 2 produces the same results as 1 and 2 3 produces the same results as 3 versions are excised from the ranges they fall within The version being tested for acceptability is then checked for membership in the resulting ranges Note that providing conflicting conditions for the same version e g 2 2 or 2 2 is meaningless and may therefore produce bizarre results when compared with actual version number s eq other requirement A requirement compares equal to another requirement if they have case insensitively equal project names version specifiers and extras The order that extras and version specifiers are in is also ignored Equal requirements also have equal hashes so that requirements can be used in sets or as dictionary keys str The string form of a Requirement is a string that if passed to Requirement parse would return an equal Requirement object project name The name of the required project key An all lowercase version of the project name useful for comparison or indexing extras A tuple of names of extras that this requirement calls for These will be all lowercase and normalized using the safe extra parsing utility function so they may not exactly equal the extras the requirement was created with specs A list of op version tuples sorted in ascending parsed version order The op in each tuple is a comparison operator represented as a string The version is the unparsed version number The relative order of tuples containing the same version numbers is undefined since having more than one operator for a given version is either redundant or self contradictory Entry Points Entry points are a simple way for distributions to advertise Python objects such as functions or classes for use by other distributions Extensible applications and frameworks can search for entry points with a particular name or group either from a specific distribution or from all active distributions on sys path and then inspect or load the advertised objects at will Entry points belong to groups which are named with a dotted name similar to a Python package or module name For example the setuptools package uses an entry point named distutils commands in order to find commands defined by distutils extensions setuptools treats the names of entry points defined in that group as the acceptable commands for a setup script In a similar way other packages can define their own entry point groups either using dynamic names within the group like distutils commands or possibly using predefined names within the group For example a blogging framework that offers various pre or post publishing hooks might define an entry point group and look for entry points named pre process and post process within that group To advertise an entry point a project needs to use setuptools and provide an entry points argument to setup in its setup script so that the entry points will be included in the distribution s metadata For more details see the setuptools documentation XXX link here to setuptools Each project distribution can advertise at most one entry point of a given name within the same entry point group For example a distutils extension could advertise two different distutils commands entry points as long as they had different names However there is nothing that prevents different projects from advertising entry points of the same name in the same group In some cases this is a desirable thing since the application or framework that uses the entry points may be calling them as hooks or in some other way combining them It is up to the application or framework to decide what to do if multiple distributions advertise an entry point some possibilities include using both entry points displaying an error message using the first one found in sys path order etc Convenience API In the following functions the dist argument can be a Distribution instance a Requirement instance or a string specifying a requirement i e project name version etc If the argument is a string or Requirement the specified distribution is located and added to sys path if not already present An error will be raised if a matching distribution is not available The group argument should be a string containing a dotted identifier identifying an entry point group If you are defining an entry point group you should include some portion of your package s name in the group name so as to avoid collision with other packages entry point groups load entry point dist group name Load the named entry point from the specified distribution or raise ImportError get entry info dist group name Return an EntryPoint object for the given group and name from the specified distribution Returns None if the distribution has not advertised a matching entry point get entry map dist group None Return the distribution s entry point map for group or the full entry map for the distribution This function always returns a dictionary even if the distribution advertises no entry points If group is given the dictionary maps entry point names to the corresponding EntryPoint object If group is None the dictionary maps group names to dictionaries that then map entry point names to the corresponding EntryPoint instance in that group iter entry points group name None 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 on sys path otherwise only ones matching both group and name are yielded Entry points are yielded from the active distributions in the order that the distributions appear on sys path Within entry points for a particular distribution however there is no particular ordering This API is actually a method of the global working set object see the section above on Basic WorkingSet Methods for more information Creating and Parsing EntryPoint name module name attrs extras dist None Create an EntryPoint instance name is the entry point name The module name is the dotted name of the module containing the advertised object attrs is an optional tuple of names to look up from the module to obtain the advertised object For example an attrs of foo bar and a module name of baz would mean that the advertised object could be obtained by the following code import baz advertised object baz foo bar The extras are an optional tuple of extra feature names that the distribution needs in order to provide this entry point When the entry point is loaded these extra features are looked up in the dist argument to find out what other distributions may need to be activated on sys path see the load method for more details The extras argument is only meaningful if dist is specified dist must be a Distribution instance EntryPoint parse src dist None classmethod 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 as is the whitespace shown between some of the items The dist argument is passed through to the EntryPoint constructor along with the other values parsed from src EntryPoint parse group group lines dist None classmethod Parse lines a string or sequence of lines to create a dictionary mapping entry point names to EntryPoint objects ValueError is raised if entry point names are duplicated if group is not a valid entry point group name or if there are any syntax errors Note the group parameter is used only for validation and to create more informative error messages If dist is provided it will be used to set the dist attribute of the created EntryPoint objects EntryPoint parse map data dist None classmethod Parse data into a dictionary mapping group names to dictionaries mapping entry point names to EntryPoint objects If data is a dictionary then the keys are used as group names and the values are passed to parse group as the lines argument If data is a string or sequence of lines it is first split into ini style sections using the split sections utility function and the section names are used as group names In either case the dist argument is passed through to parse group so that the entry points will be linked to the specified distribution EntryPoint Objects For simple introspection EntryPoint objects have attributes that correspond exactly to the constructor argument names name module name attrs extras and dist are all available In addition the following methods are provided load require True env None installer None Load the entry point returning the advertised Python object or raise ImportError if it cannot be obtained If require is a true value then require env installer is called before attempting the import require env None installer None Ensure that any extras needed by the entry point are available on sys path UnknownExtra is raised if the EntryPoint has extras but no dist or if the named extras are not defined by the distribution If env is supplied it must be an Environment and it will be used to search for needed distributions if they are not already present on sys path If installer is supplied it must be a callable taking a Requirement instance and returning a matching importable Distribution instance or None str The string form of an EntryPoint is a string that could be passed to EntryPoint parse to produce an equivalent EntryPoint Distribution Objects Distribution objects represent collections of Python code that may or may not be importable and may or may not have metadata and resources associated with them Their metadata may include information such as what other projects the distribution depends on what entry points the distribution advertises and so on Getting or Creating Distributions Most commonly you ll obtain Distribution objects from a WorkingSet or an Environment See the sections above on WorkingSet Objects and Environment Objects which are containers for active distributions and available distributions respectively You can also obtain Distribution objects from one of these high level APIs find distributions path item only False Yield distributions accessible via path item If only is true yield only distributions whose location is equal to path item In other words if only is true this yields any distributions that would be importable if path item were on sys path If only is false this also yields distributions that are in or under path item but would not be importable unless their locations were also added to sys path get distribution dist spec Return a Distribution object for a given Requirement or string If dist spec is already a Distribution instance it is returned If it is a Requirement object or a string that can be parsed into one it is used to locate and activate a matching distribution which is then returned However if you re creating specialized tools for working with distributions or creating a new distribution format you may also need to create Distribution objects directly using one of the three constructors below These constructors all take an optional metadata argument which is used to access any resources or metadata associated with the distribution metadata must be an object that implements the IResourceProvider interface or None If it is None an EmptyProvider is used instead Distribution objects implement both the IResourceProvider and IMetadataProvider Methods by delegating them to the metadata object Distribution from location location basename metadata None kw classmethod Create a distribution for location which must be a string such as a URL filename or other string that might be used on sys path basename is a string naming the distribution like Foo 1 2 py2 4 egg If basename ends with egg then the project s name version python version and platform are extracted from the filename and used to set those properties of the created distribution Any additional keyword arguments are forwarded to the Distribution constructor Distribution from filename filename metadata None kw classmethod Create a distribution by parsing a local filename This is a shorter way of saying Distribution from location normalize path filename os path basename filename metadata In other words it creates a distribution whose location is the normalize form of the filename parsing name and version information from the base portion of the filename Any additional keyword arguments are forwarded to the Distribution constructor Distribution location metadata project name version py version platform precedence Create a distribution by setting its properties All arguments are optional and default to None except for py version which defaults to the current Python version and precedence which defaults to EGG DIST for more details see precedence under Distribution Attributes below Note that it s usually easier to use the from filename or from location constructors than to specify all these arguments individually Distribution Attributes location A string indicating the distribution s location For an importable distribution this is the string that would be added to sys path to make it actively importable For non importable distributions this is simply a filename URL or other way of locating the distribution project name A string naming the project that this distribution is for Project names are defined by a project s setup script and they are used to identify projects on PyPI When a Distribution is constructed the project name argument is passed through the safe name utility function to filter out any unacceptable characters key dist key is short for dist project name lower It s used for case insensitive comparison and indexing of distributions by project name extras A list of strings giving the names of extra features defined by the project s dependency list the extras require argument specified in the project s setup script version A string denoting what release of the project this distribution contains When a Distribution is constructed the version argument is passed through the safe version utility function to filter out any unacceptable characters If no version is specified at construction time then attempting to access this attribute later will cause the Distribution to try to discover its version by reading its PKG INFO metadata file If PKG INFO is unavailable or can t be parsed ValueError is raised parsed version The parsed version is a tuple representing a parsed form of the distribution s version dist parsed version is a shortcut for calling parse version dist version It is used to compare or sort distributions by version See the Parsing Utilities section below for more information on the parse version function Note that accessing parsed version may result in a ValueError if the Distribution was constructed without a version and without metadata capable of supplying the missing version info py version The major minor Python version the distribution supports as a string For example 2 3 or 2 4 The default is the current version of Python platform A string representing the platform the distribution is intended for or None if the distribution is pure Python and therefore cross platform See Platform Utilities below for more information on platform strings precedence A distribution s precedence is used to determine the relative order of two distributions that have the same project name and parsed version The default precedence is pkg resources EGG DIST which is the highest i e most preferred precedence The full list of predefined precedences from most preferred to least preferred is EGG DIST BINARY DIST SOURCE DIST CHECKOUT DIST and DEVELOP DIST Normally precedences other than EGG DIST are used only by the setuptools package index module when sorting distributions found in a package index to determine their suitability for installation System and Development eggs i e ones that use the egg info format however are automatically given a precedence of DEVELOP DIST Distribution Methods activate path None Ensure distribution is importable on path If path is None sys path is used instead This ensures that the distribution s location is in the path list and it also performs any necessary namespace package fixups or declarations That is if the distribution contains namespace packages this method ensures that they are declared and that the distribution s contents for those namespace packages are merged with the contents provided by any other active distributions See the section above on Namespace Package Support for more information pkg resources adds a notification callback to the global working set that ensures this method is called whenever a distribution is added to it Therefore you should not normally need to explicitly call this method Note that this means that namespace packages on sys path are always imported as soon as pkg resources is which is another reason why namespace packages should not contain any code or import statements as requirement Return a Requirement instance that matches this distribution s project name and version requires extras List the Requirement objects that specify this distribution s dependencies If extras is specified it should be a sequence of names of extras defined by the distribution and the list returned will then include any dependencies needed to support the named extras clone kw Create a copy of the distribution Any supplied keyword arguments override the corresponding argument to the Distribution constructor allowing you to change some of the copied distribution s attributes egg name Return what this distribution s standard filename should be not including the egg extension For example a distribution for project Foo version 1 2 that runs on Python 2 3 for Windows would have an egg name of Foo 1 2 py2 3 win32 Any dashes in the name or version are converted to underscores Distribution from location will convert them back when parsing a egg file name cmp other hash Distribution objects are hashed and compared on the basis of their parsed version and precedence followed by their key lowercase project name location Python version and platform The following methods are used to access EntryPoint objects advertised by the distribution See the section above on Entry Points for more detailed information about these operations get entry info group name Return the EntryPoint object for group and name or None if no such point is advertised by this distribution get entry map group None Return the entry point map for group If group is None return a dictionary mapping group names to entry point maps for all groups An entry point map is a dictionary of entry point names to EntryPoint objects load entry point group name Short for get entry info group name load Returns the object advertised by the named entry point or raises ImportError if the entry point isn t advertised by this distribution or there is some other import problem In addition to the above methods Distribution objects also implement all of the IResourceProvider and IMetadataProvider Methods which are documented in later sections has metadata name metadata isdir name metadata listdir name get metadata name get metadata lines name run script script name namespace get resource filename manager resource name get resource stream manager resource name get resource string manager resource name has resource resource name resource isdir resource name resource listdir resource name If the distribution was created with a metadata argument these resource and metadata access methods are all delegated to that metadata provider Otherwise they are delegated to an EmptyProvider so that the distribution will appear to have no resources or metadata This delegation approach is used so that supporting custom importers or new distribution formats can be done simply by creating an appropriate IResourceProvider implementation see the section below on Supporting Custom Importers for more details ResourceManager API The ResourceManager class provides uniform access to package resources whether those resources exist as files and directories or are compressed in an archive of some kind Normally you do not need to create or explicitly manage ResourceManager instances as the pkg resources module creates a global instance for you and makes most of its methods available as top level names in the pkg resources module namespace So for example this code actually calls the resource string method of the global ResourceManager import pkg resources my data pkg resources resource string name foo dat Thus you can use the APIs below without needing an explicit ResourceManager instance just import and use them as needed Basic Resource Access In the following methods the package or requirement argument may be either a Python package module name e g foo bar or a Requirement instance If it is a package or module name the named module or package must be importable i e be in a distribution or directory on sys path and the resource name argument is interpreted relative to the named package Note that if a module name is used then the resource name is relative to the package immediately containing the named module Also you should not use use a namespace package name because a namespace package can be spread across multiple distributions and is therefore ambiguous as to which distribution should be searched for the resource If it is a Requirement then the requirement is automatically resolved searching the current Environment if necessary and a matching distribution is added to the WorkingSet and sys path if one was not already present Unless the Requirement can t be satisfied in which case an exception is raised The resource name argument is then interpreted relative to the root of the identified distribution i e its first path segment will be treated as a peer of the top level modules or packages in the distribution Note that resource names must be separated paths and cannot be absolute i e no leading or contain relative names like Do not use os path routines to manipulate resource paths as they are not filesystem paths resource exists package or requirement resource name Does the named resource exist Return True or False accordingly resource stream package or requirement resource name Return a readable file like object for the specified resource it may be an actual file a StringIO or some similar object The stream is in binary mode in the sense that whatever bytes are in the resource will be read as is resource string package or requirement resource name Return the specified resource as a string The resource is read in binary fashion such that the returned string contains exactly the bytes that are stored in the resource resource isdir package or requirement resource name Is the named resource a directory Return True or False accordingly resource listdir package or requirement resource name List the contents of the named resource directory just like os listdir except that it works even if the resource is in a zipfile Note that only resource exists and resource isdir are insensitive as to the resource type You cannot use resource listdir on a file resource and you can t use resource string or resource stream on directory resources Using an inappropriate method for the resource type may result in an exception or undefined behavior depending on the platform and distribution format involved Resource Extraction resource filename package or requirement resource name Sometimes it is not sufficient to access a resource in string or stream form and a true filesystem filename is needed In such cases you can use this method or module level function to obtain a filename for a resource If the resource is in an archive distribution such as a zipped egg it will be extracted to a cache directory and the filename within the cache will be returned If the named resource is a directory then all resources within that directory including subdirectories are also extracted If the named resource is a C extension or eager resource see the setuptools documentation for details then all C extensions and eager resources are extracted at the same time Archived resources are extracted to a cache location that can be managed by the following two methods set extraction path path 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 resource provider 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 On Windows for example you can t unlink pyd or dll files that are still in use Note that you may not change the extraction path for a given resource manager once resources have been extracted unless you first call cleanup resources cleanup resources force False 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 Provider Interface If you are implementing an IResourceProvider and or IMetadataProvider for a new distribution archive format you may need to use the following IResourceManager methods to co ordinate extraction of resources to the filesystem If you re not implementing an archive format however you have no need to use these methods Unlike the other methods listed above they are not available as top level functions tied to the global ResourceManager you must therefore have an explicit ResourceManager instance to use them get cache path archive name names 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 extraction error Raise an ExtractionError describing the active exception as interfering with the extraction process You should call this if you encounter any OS errors extracting the file to the cache path it will format the operating system exception for you and add other information to the ExtractionError instance that may be needed by programs that want to wrap or handle extraction errors themselves postprocess tempname filename Perform any platform specific postprocessing of tempname 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 Metadata API The metadata API is used to access metadata resources bundled in a pluggable distribution Metadata resources are virtual files or directories containing information about the distribution such as might be used by an extensible application or framework to connect plugins Like other kinds of resources metadata resource names are separated and should not contain or begin with a You should not use os path routines to manipulate resource paths The metadata API is provided by objects implementing the IMetadataProvider or IResourceProvider interfaces Distribution objects implement this interface as do objects returned by the get provider function get provider package or requirement If a package name is supplied return an IResourceProvider for the package If a Requirement is supplied resolve it by returning a Distribution from the current working set searching the current Environment if necessary and adding the newly found Distribution to the working set If the named package can t be imported or the Requirement can t be satisfied an exception is raised NOTE if you use a package name rather than a Requirement the object you get back may not be a pluggable distribution depending on the method by which the package was installed In particular development packages and single version externally managed packages do not have any way to map from a package name to the corresponding project s metadata Do not write code that passes a package name to get provider and then tries to retrieve project metadata from the returned object It may appear to work when the named package is in an egg file or directory but it will fail in other installation scenarios If you want project metadata you need to ask for a project not a package IMetadataProvider Methods The methods provided by objects such as Distribution instances that implement the IMetadataProvider or IResourceProvider interfaces are has metadata name Does the named metadata resource exist metadata isdir name Is the named metadata resource a directory metadata listdir name List of metadata names in the directory like os listdir get metadata name Return the named metadata resource as a string The data is read in binary mode i e the exact bytes of the resource file are returned get metadata lines name Yield named metadata resource as list of non blank non comment lines This is short for calling yield lines provider get metadata name See the section on yield lines below for more information on the syntax it recognizes run script script name namespace Execute the named script in the supplied namespace dictionary Raises ResolutionError if there is no script by that name in the scripts metadata directory namespace should be a Python dictionary usually a module dictionary if the script is being run as a module Exceptions pkg resources provides a simple exception hierarchy for problems that may occur when processing requests to locate and activate packages ResolutionError DistributionNotFound VersionConflict UnknownExtra ExtractionError ResolutionError This class is used as a base class for the other three exceptions so that you can catch all of them with a single except clause It is also raised directly for miscellaneous requirement resolution problems like trying to run a script that doesn t exist in the distribution it was requested from DistributionNotFound A distribution needed to fulfill a requirement could not be found VersionConflict The requested version of a project conflicts with an already activated version of the same project UnknownExtra One of the extras requested was not recognized by the distribution it was requested from ExtractionError A problem occurred extracting a resource to the Python Egg cache The following attributes are available on instances of this exception manager The resource manager that raised this exception cache path The base directory for resource extraction original error The exception instance that caused extraction to fail Supporting Custom Importers By default pkg resources supports normal filesystem imports and zipimport importers If you wish to use the pkg resources features with other PEP 302 compatible importers or module loaders you may need to register various handlers and support functions using these APIs register finder importer type distribution finder 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 when passed a path item the importer instance and an only flag yields Distribution instances found under that path item The only flag if true means the finder should yield only Distribution objects whose location is equal to the path item provided See the source of the pkg resources find on path function for an example finder function register loader type loader type provider factory Register provider factory to make IResourceProvider objects for loader type loader type is the type or class of a PEP 302 module loader and provider factory is a function that when passed a module object returns an IResourceProvider for that module allowing it to be used with the ResourceManager API register namespace handler importer type namespace handler Register namespace handler to declare namespace packages for the given importer type importer type is the type or class of a PEP 302 importer sys path item handler and namespace handler is a callable with a signature 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 relevant importer object has already agreed that it can handle the relevant path item The handler should only return a subpath if the module path does not already contain an equivalent subpath Otherwise it should return None For an example namespace handler see the source of the pkg resources file ns handler function which is used for both zipfile

    Original URL path: http://peak.telecommunity.com/DevCenter/PkgResources?action=LikePages (2016-04-24)
    Open archived version from archive



  •