Reputation: 18102
In their setup.py Python packages provides some information. This information can then be found in the PKG_INFO file of the egg.
How can I access them once I have installed the package?
For instance, if I have the following module:
setup(name='myproject',
version='1.2.0.dev0',
description='Demo of a setup.py file.',
long_description=README + "\n\n" + CHANGELOG + "\n\n" + CONTRIBUTORS,
license='Apache License (2.0)',
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
"License :: OSI Approved :: Apache Software License"
],
keywords="web sync json storage services",
url='https://github.com/Kinto/kinto')
How can I use Python to get back the information provided in the setup.py?
I was thinking of something similar to that:
import pkg_resource
url = pkg_resource.get_distribution(__package__).url
Any idea?
Upvotes: 4
Views: 596
Reputation: 3910
Starting from python 3.8, you can use importlib.metadata
to extract metadata of a package.
For example, to extract metadata of urllib3
:
>>> from importlib import metadata
>>> import urllib3
>>> list(metadata.metadata('urllib3'))
['Metadata-Version', 'Name', 'Version', 'Summary', 'Home-page', 'Author', 'Author-email', 'License', 'Project-URL', 'Project-URL', 'Project-URL', 'Description', 'Keywords', 'Platform', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Requires-Python', 'Provides-Extra', 'Provides-Extra', 'Provides-Extra']
>>> metadata.metadata('urllib3')['Version']
'1.25.8'
>>> metadata.metadata('urllib3')['Project-URL']
'Documentation, https://urllib3.readthedocs.io/'
Upvotes: 0
Reputation: 21
I wish we could do better.
Actually, we can. There is no need to use the private method, we might just do:
import pkg_resources
import distutils
import io
distribution = pkg_resources.get_distribution(__package__)
metadata_str = distribution.get_metadata(distribution.PKG_INFO)
metadata_obj = distutils.dist.DistributionMetadata()
metadata_obj.read_pkg_file(io.StringIO(metadata_str))
url = metadata_obj.url
Upvotes: 1
Reputation: 18102
There is apparently a private API that let you do that with pkg_resources
:
import pkg_resources
d = pkg_resources.get_distribution(__package__)
metadata = d._get_metadata(d.PKG_INFO)
home_page = [m for m in metadata if m.startswith('Home-page:')]
url = home_page[0].split(':', 1)[1].strip()
I wish we could do better.
Upvotes: 2