Skip to content

Instantly share code, notes, and snippets.

@krisselden
Created September 27, 2024 20:14
Show Gist options
  • Save krisselden/ab5d1a31cc72716f05645771a8b51c55 to your computer and use it in GitHub Desktop.
Save krisselden/ab5d1a31cc72716f05645771a8b51c55 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import importlib.metadata
import importlib.util
import pathlib
import site
import sys
if len(sys.argv) != 2:
print("Usage: python find_distribution.py <module>")
exit()
spec = importlib.util.find_spec(sys.argv[1])
if spec is None:
print("Module not found")
exit()
if spec.origin is None:
print("Module not found")
exit()
spec_path = pathlib.Path(spec.origin)
def find_dist(search_path: pathlib.Path) -> importlib.metadata.Distribution | None:
for dist in importlib.metadata.distributions(path=site.getsitepackages()):
dist_files = dist.files
if dist_files is None:
continue
for file in dist_files:
file_path = dist.locate_file(file)
if file_path == search_path:
return dist
return None
dist = find_dist(spec_path)
if dist is None:
print("Distribution not found")
exit()
print(dist.name, dist.version)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment