Finding an associated Python package name and version, given a path

Hi all!
I’m looking for a way to get the Python package name and version, given a path. The path could be the main python packages directory (which contains all the installed Python packages), one of the packages’ directory, some file/directory inside the package directory.

Example to make it more clear: Lets look at /tmp/vendor. This directory contains all the packages I installed using pip. So for example, if requests package is installed there, then I have /tmp/vendor/requests/ and other files/directory which are the source code of requests. Given this file (as example), I want to know that this file is associated with requests package with 2.26.0 version.

I was trying to use pkg_resources. That package provides find_distributions method which can return all the packages inside /tmp/vendor, by running:

distributions = pkg_resources.find_distributions('/tmp/vendor')
for current_distribution in distributions:
    print('Found package', current_distribution .project_name, '==', current_distribution .version)

It didn’t work to run it on /tmp/vendor/requests/` or even /tmp/vendor/requests`. I’m looking for an algorithm to find a related Python package, given a path (file/directory inside the packages). Is there a way to achieve it?

Please note that this question is the next step of my previous research on the matter.
Thank you in advance.

EDIT: The packages location could be of some Python version. It could be Python3.6, Python2.7 and others. For example, for /tmp/vendor I used Python3.6 but I want the utility to be generic as possible, given some packages area (that were installed with some specific Python version).

I don’t know exactly what APIs already exist for this, but the high-level operation would look like enumerating every installed distribution (i.e. via the dist-info directories) and checking the RECORD file to see whether it installed the file you know about.

There isn’t any mapping from installed file to distribution, only the one I described above from distribution to files. So you need to do a search (or a heuristic, since some distributions have an obviously named package that contains all of its files).

1 Like

importlib.metadata is the stdlib one. You should check the docs for the Python version you’re using, the package was provisional until 3.10 and the API changed somewhat between versions. There’s a backport on PyPI if you want the same API across versions.

Is that what you are looking for?

You received quite a lot of suggestions on your StackOverflow post, but did not really explain much why they do not fit your needs, so it is hard to help you further.

Are we sure that those installed libraries were installed properly and have proper metadata?