Laurent Cesaro
Laurent Cesaro

Reputation: 341

Python print version libraries used in script

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
# ...

Upvotes: 0

Views: 915

Answers (2)

Dorian Turba
Dorian Turba

Reputation: 3735

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()

Upvotes: 1

MaPy
MaPy

Reputation: 505

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())

Upvotes: 0

Related Questions