Solution
Although I prefer using importlib.metadata
, since there is another answer already showing how to do that, I will show you another alternative.
For the purpose of illustration, I will use one of my own packages genespeak
from PyPI.
With metadata
try:
from importlib import metadata
except ImportError: # for Python<3.8
import importlib_metadata as metadata
print(metadata.name('genespeak')) # genespeak
print(metadata.version('genespeak')) # 0.0.7
Use pkginfo
PyPI
We will use the following 5 ways of accessing package information.
from pkginfo import SDist, BDist, Wheel, Installed, Develop
A. Check Package Info from Source Distributions
Typically you would create the source distribution file with:
python setup.py sdist
Assuming you have a .tar.gz
file at path: ./dist/genespeak-0.0.7.tar.gz
, here is what you need to extract the package info.
from pkginfo import SDist
pkg = SDist("./dist/genespeak-0.0.7.tar.gz")
# Now you can access the metadata fields from
# PKG-INFO file inside the source file:
# `./dist/genespeak-0.0.7.tar.gz`
print(pkg.name) # genespeak
print(pkg.version) # 0.0.7
B. Check Package Info from Binary Distributions
Typically you would create the binary distribution files (.egg
) with:
python setup.py bdist_egg
Assuming you have a .egg
file at path: ./dist/genespeak-0.0.7-py38.egg
, here is what you need to extract the package info.
from pkginfo import BDist
pkg = BDist("./dist/genespeak-0.0.7-py38.egg")
# Now you can access the metadata fields from
# the binary distribution file (*.egg):
# `./dist/genespeak-0.0.7-py38.egg`
print(pkg.name) # genespeak
print(pkg.version) # 0.0.7
C. Check Package Info from Wheel
Typically you would create the binary distribution wheel files (.whl
) with:
python setup.py bdist_wheel
Assuming you have a .whl
file at path: ./dist/genespeak-0.0.7-py3-none-any-whl
, here is what you need to extract the package info.
from pkginfo import Wheel
pkg = Wheel("./dist/genespeak-0.0.7-py3-none-any-whl")
# Now you can access the metadata fields from
# PKG-INFO file inside the source file:
# `./dist/genespeak-0.0.7-py3-none-any.whl`
print(pkg.name) # genespeak
print(pkg.version) # 0.0.7
D. Check Package Info from Installed Packages
See here for more details
from pkginfo import Installed
import genespeak
pkg = Installed(genespeak)
# Now you can access the metadata fields from
# PKG-INFO file inside the source file:
# `./dist/genespeak-0.0.7.tar.gz`
print(pkg.name) # genespeak
print(pkg.version) # 0.0.7
E. Check Package Info from Development Directory
from pkginfo import Develop
dev = Develop(".")
# Now you can access the metadata fields from
# PKG-INFO file under `genespeak.egg-info`
# directory under the project root.
print(dev.name) # genespeak
print(dev.version) # 0.0.7
References