List of actual import names in python

With pip freeze I get a list of package names. eg:.

Django==1.9.7 psycopg2==2.6.1 djangorestframework==3.3.3 djangorestframework-jwt==1.8.0 django-rest-swagger==0.3.7 django-environ==0.4.0 python-dateutil==2.5.3 django-sendfile==0.3.10 

Is there a way to get a list of actual names for import ? e.g. instead of djangorestframework => rest_framework

+8
python pip
source share
3 answers

Yes, top_level.txt will be the correct module name. You can use the pkg_resources module to extract metadata from packages.

Python code for this:

 import pkg_resources def read_requirements(requirements_file): with open(requirements_file, 'r') as f: return f.read().splitlines() def get_package_name(package): return list(pkg_resources.get_distribution(package)._get_metadata('top_level.txt'))[0] requirements = read_requirements('/path/to/requirements.txt') packages = [get_package_name(p) for p in requirements] 
+3
source share

You can use the standard pkgutil module to get a top-level import list, for example:

 import pkgutil list(pkgutil.iter_modules()) 

It will only search for modules that live in regular files, zip files or another bootloader that support enumeration of modules. Most of them should be on a standard system.

The result is a list of 3 tuples with a loader, the name of the module and whether it is a single module or package. If you are only interested in the module name, just do:

 list(item[1] for item in pkgutil.iter_modules()) 
+6
source share

Another way is to look at the first line of this file:

 # If output of pip freeze is djangorestframework==3.3.3 # Then your dir prefix becomes "djangorestframework-3.3.3" ../lib/python2.7/site-packages/<dir-prefix>.dist-info/top_level.txt # eg ../lib/python2.7/site-packages/djangorestframework-3.3.3.dist-info/top_level.txt 
+1
source share

All Articles