You can get the version of a python distribution using
import pkg_resources
pkg_resources.get_distribution("distro").version
This is great if you know the distribution name, however I need to dynamically figure out my distribution name at runtime.
# Common framework base app class, extended by each app
class App(object):
def get_app_version(self) -> str:
package_name = self.__class__.__module__.split('.')[0]
try:
return pkg_resources.get_distribution(package_name).version
except Exception:
return "development"
This works for cases where the app's package name is the same as the distribution name (e.g. requests
). However this fails once they don't match (e.g. my-app
containing package my_app
).
So what I need is a mapping between distributions and their packages, which I'm sure must exist somewhere since pip seems to know what to delete when you call uninstall:
$ pip uninstall requests
Uninstalling requests-2.21.0:
Would remove:
/home/user/.virtualenvs/app/lib/python3.6/site-packages/requests-2.21.0.dist-info/*
/home/user/.virtualenvs/app/lib/python3.6/site-packages/requests/*
How do I programatically access this mapping?