0

I would like to know if there is a way to check the version of all libraries used in a python 3.+ script.

In example:

import check_version # example  
import boto3
import numpy
import time
import pandas

print(check_version.all_libraries)
# result
# boto3==1.2
# numpy==2.6
# ...
Dorian Turba
  • 3,260
  • 3
  • 23
  • 67
Laurent Cesaro
  • 341
  • 1
  • 3
  • 17
  • Does this answer your question? [How to list imported modules?](https://stackoverflow.com/questions/4858100/how-to-list-imported-modules) – Dorian Turba Apr 22 '21 at 09:14
  • Does this answer your question? [How to check version of python modules?](https://stackoverflow.com/questions/20180543/how-to-check-version-of-python-modules) – Tomerikoo Apr 22 '21 at 10:03

2 Answers2

1

This might helps you How to list imported modules?, but you have to send the scope where your modules are imported to the function with locals() or globals(), otherwise:

This won't return local imports

Non-module imports like from x import y won't be listed because it can be any python object (variables of any types, classes, functions, etc).

# check_version.py
from types import ModuleType


def all_libraries(scope):
    return [f'{value.__name__}=={getattr(value, "__version__", "NA")}' for _, value in scope.items()
            if isinstance(value, ModuleType) and value.__name__ != 'builtins']
from check_version import all_libraries

def foobar():
    # print globals imports
    for modules_version in all_libraries(globals()):
        print(modules_version)
    # time = NA
    # random = NA

    # print locals imports
    import PIL
    import sys
    for modules_version in all_libraries(locals()):
        print(modules_version)
    # sys=NA
    # PIL=5.1.0

foobar()
Dorian Turba
  • 3,260
  • 3
  • 23
  • 67
0

Try the following:

import types


def imports():
    for name, val in globals().items():
        if isinstance(val, types.ModuleType):
            try:
                yield val.__name__, val.__version__
            except:
                yield val.__name__,'no version available for built ins'
                
list(imports())
MaPy
  • 505
  • 1
  • 6
  • 9