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

2024/11/20 16:39:15

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

Here is a copy-pasteable snippet which will print your packages.

Requires: prettytable (pip install prettytable)

Code

import pkg_resources
import prettytabledef get_pkg_license(pkg):try:lines = pkg.get_metadata_lines('METADATA')except:lines = pkg.get_metadata_lines('PKG-INFO')for line in lines:if line.startswith('License:'):return line[9:]return '(Licence not found)'def print_packages_and_licenses():t = prettytable.PrettyTable(['Package', 'License'])for pkg in sorted(pkg_resources.working_set, key=lambda x: str(x).lower()):t.add_row((str(pkg), get_pkg_license(pkg)))print(t)if __name__ == "__main__":print_packages_and_licenses()

Example Output

+---------------------------+--------------------------------------------------------------+
|          Package          |                           License                            |
+---------------------------+--------------------------------------------------------------+
|       appdirs 1.4.3       |                             MIT                              |
|     argon2-cffi 16.3.0    |                             MIT                              |
|        boto3 1.4.4        |                      Apache License 2.0                      |
|      botocore 1.5.21      |                      Apache License 2.0                      |
|        cffi 1.10.0        |                             MIT                              |
|       colorama 0.3.9      |                             BSD                              |
|      decorator 4.0.11     |                       new BSD License                        |
|        Django 1.11        |                             BSD                              |
|  django-debug-toolbar 1.7 |                             BSD                              |
|    django-environ 0.4.3   |                         MIT License                          |
|   django-storages 1.5.2   |                             BSD                              |
|    django-uuslug 1.1.8    |                             BSD                              |
| djangorestframework 3.6.2 |                             BSD                              |
|      docutils 0.13.1      | public domain, Python, 2-Clause BSD, GPL 3 (see COPYING.txt) |
|     EasyProcess 0.2.3     |                             BSD                              |
|       ipython 6.0.0       |                             BSD                              |
|   ipython-genutils 0.2.0  |                             BSD                              |
|        jedi 0.10.2        |                             MIT                              |
|       jmespath 0.9.1      |                             MIT                              |
|       packaging 16.8      |              BSD or Apache License, Version 2.0              |
|     pickleshare 0.7.4     |                             MIT                              |
|         pip 9.0.1         |                             MIT                              |
|     prettytable 0.7.2     |                        BSD (3 clause)                        |
|   prompt-toolkit 1.0.14   |                           UNKNOWN                            |
|       psycopg2 2.6.2      |                 LGPL with exceptions or ZPL                  |
|       pycparser 2.17      |                             BSD                              |
|       Pygments 2.2.0      |                         BSD License                          |
|      pyparsing 2.2.0      |                         MIT License                          |
|   python-dateutil 2.6.0   |                        Simplified BSD                        |
|    python-slugify 1.2.4   |                             MIT                              |
|        pytz 2017.2        |                             MIT                              |
|   PyVirtualDisplay 0.2.1  |                             BSD                              |
|     s3transfer 0.1.10     |                      Apache License 2.0                      |
|       selenium 3.0.2      |                           UNKNOWN                            |
|     setuptools 35.0.2     |                           UNKNOWN                            |
|    simplegeneric 0.8.1    |                           ZPL 2.1                            |
|         six 1.10.0        |                             MIT                              |
|       sqlparse 0.2.3      |                             BSD                              |
|      traitlets 4.3.2      |                             BSD                              |
|      Unidecode 0.4.20     |                             GPL                              |
|       wcwidth 0.1.7       |                             MIT                              |
|       wheel 0.30.0a0      |                             MIT                              |
|  win-unicode-console 0.5  |                             MIT                              |
+---------------------------+--------------------------------------------------------------+
https://en.xdnf.cn/q/26299.html

Related Q&A

Convert DataFrameGroupBy object to DataFrame pandas

I had a dataframe and did a groupby in FIPS and summed the groups that worked fine.kl = ks.groupby(FIPS)kl.aggregate(np.sum)I just want a normal Dataframe back but I have a pandas.core.groupby.DataFram…

Correct way to obtain confidence interval with scipy

I have a 1-dimensional array of data:a = np.array([1,2,3,4,4,4,5,5,5,5,4,4,4,6,7,8])for which I want to obtain the 68% confidence interval (ie: the 1 sigma).The first comment in this answer states that…

How to supply a mock class method for python unit test?

Lets say I have a class like this. class SomeProductionProcess(CustomCachedSingleTon):@classmethoddef loaddata(cls):"""Uses an iterator over a large file in Production for the Data pipel…

View pdf image in an iPython Notebook

The following code allows me to view a png image in an iPython notebook. Is there a way to view pdf image? I dont need to use IPython.display necessarily. I am looking for a way to print a pdf image i…

Is the use of del bad?

I commonly use del in my code to delete objects:>>> array = [4, 6, 7, hello, 8] >>> del(array[array.index(hello)]) >>> array [4, 6, 7, 8] >>> But I have heard many …

Find how many lines in string

I am creating a python movie player/maker, and I want to find the number of lines in a multiple line string. I was wondering if there was any built in function or function I could code to do this:x = &…

AttributeError: Cant get attribute new_block on module pandas.core.internals.blocks

I was using pyspark on AWS EMR (4 r5.xlarge as 4 workers, each has one executor and 4 cores), and I got AttributeError: Cant get attribute new_block on <module pandas.core.internals.blocks. Below is…

Disable python import sorting in VSCode

I am trying to disable vscode from formatting my python imports when I save my file. I have some code that must run in between various imports so order is important, but every time I save it just shove…

Log-log lmplot with seaborn

Can Seaborns lmplot plot on log-log scale? This is lmplot with linear axes: import numpy as np import pandas as pd import seaborn as sns x = 10**arange(1, 10) y = 10** arange(1,10)*2 df1 = pd.DataFra…

Django on IronPython

I am interested in getting an install of Django running on IronPython, has anyone had any success getting this running with some level of success? If so can you please tell of your experiences, perfo…