Can pip (or setuptools, distribute etc...) list the license used by each installed package?

Jacob Rigby picture Jacob Rigby · Sep 30, 2013 · Viewed 14.6k times · Source

I'm trying to audit a Python project with a large number of dependencies and while I can manually look up each project's homepage/license terms, it seems like most OSS packages should already contain the license name and version in their metadata.

Unfortunately I can't find any options in pip or easy_install to list more than the package name and installed version (via pip freeze).

Does anyone have pointers to a tool to list license metadata for Python packages?

Answer

dkamins picture dkamins · Sep 30, 2013

You can use pkg_resources:

import pkg_resources

def get_pkg_license(pkgname):
    """
    Given a package reference (as from requirements.txt),
    return license listed in package metadata.
    NOTE: This function does no error checking and is for
    demonstration purposes only.
    """
    pkgs = pkg_resources.require(pkgname)
    pkg = pkgs[0]
    for line in pkg.get_metadata_lines('PKG-INFO'):
        (k, v) = line.split(': ', 1)
        if k == "License":
            return v
    return None

Example use:

>>> get_pkg_license('mercurial')
'GNU GPLv2+'
>>> get_pkg_license('pytz')
'MIT'
>>> get_pkg_license('django')
'UNKNOWN'