Home > Software engineering >  Get name of installation directory for pip installed package
Get name of installation directory for pip installed package

Time:12-24

I need to get the installation directory of a Python3 package installed using pip.

I got a package, let's say mkdocs-mermaid2-plugin.

pip install mkdocs-mermaid2-plugin // being installed to site-packages/mermaid2

If I use this package within Python, i can do so import mermaid2.

I need a script, which outputs for a given Python package name mkdocs-mermaid2-plugin the name of the installation directory.

$ ./print-installation-directory-of-package.py mkdocs-mermaid2-plugin
mermaid2

CodePudding user response:

You can do this via pip commands

pip show mkdocs-mermaid2-plugin

this will show all info about that pip package

If you want to get info on what packages are installed you can do

pip list

Example:

pip show xkit

returns

Name: xkit
Version: 0.0.0
Summary: library for the manipulation of the xorg.conf
Home-page: https://launchpad.net/x-kit
Author: Alberto Milone
Author-email: [email protected]
License: GPL v2 or later
Location: /usr/lib/python3/dist-packages
Requires:
Required-by:

if you just want to return only the location you can do this by using the following

pip show xkit | grep -F Location

CodePudding user response:

Usage:

$ ./print-directory-of-module.py mkdocs-mermaid2-plugin
mermaid2

Source:

#!/usr/bin/env python
import os
import sys
import importlib.metadata
from importlib.metadata import distribution

args = sys.argv[1:]
if len(args) > 0:
  try:
    dist = distribution(args[0])
  except importlib.metadata.PackageNotFoundError as e:
    print('Package {} not found'.format(e), file=sys.stderr)
    sys.exit(1)

  pathToTopLevelFile = os.path.join(dist._path, "top_level.txt")
  f = open(pathToTopLevelFile)

  print(f.read().strip())

This solution works - but is ugly as hell, there must be a better way.

  • Related