Skip to content

Instantly share code, notes, and snippets.

@sri-teja
Last active October 17, 2019 10:10
Show Gist options
  • Save sri-teja/ca25078732bf47ea0c60c3007dc0af0c to your computer and use it in GitHub Desktop.
Save sri-teja/ca25078732bf47ea0c60c3007dc0af0c to your computer and use it in GitHub Desktop.
This is a python code which gives the list of loaded packages in the current environment. *Source:* stack overflow, link given in the code.
# show versions of packages
# adopted from https://stackoverflow.com/questions/40428931/package-for-listing-version-of-packages-used-in-a-jupyter-notebook
import sys
import pkg_resources
import types
def get_imports():
for name, val in globals().items():
if isinstance(val, types.ModuleType):
# Split ensures you get root package,
# not just imported function
name = val.__name__.split(".")[0]
elif isinstance(val, type):
name = val.__module__.split(".")[0]
# Some packages are weird and have different
# imported names vs. system/pip names. Unfortunately,
# there is no systematic way to get pip names from
# a package's imported name. You'll have to add
# exceptions to this list manually!
poorly_named_packages = {
"PIL": "Pillow",
"sklearn": "scikit-learn"
}
if name in poorly_named_packages.keys():
name = poorly_named_packages[name]
yield name.lower()
imports = list(set(get_imports()))
# The only way I found to get the version of the root package
# from only the name of the package is to cross-check the names
# of installed packages vs. imported packages
modules = []
for m in sys.builtin_module_names:
if m.lower() in imports and m !='builtins':
# modules.append((m,'Python BuiltIn'))
imports.remove(m.lower())
for m in pkg_resources.working_set:
if m.project_name.lower() in imports and m.project_name!="pip":
modules.append((m.project_name, m.version))
imports.remove(m.project_name.lower())
for r in modules:
print("{}=={}".format(*r))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment