Python:获取由我的脚本导入的外部模块的完整列表及其版本

时间:2017-08-24 12:39:32

标签: python python-module

在我的脚本中,我以这种方式导入了5个外部模块:

import numpy as np
import scipy.io as sio
import pandas
import IPython
from termcolor import cprint

我想获得上面导入的外部模块和版本的完整列表,因此我编写了以下脚本:

    def imports():
        modulesList = []
        for name, val in globals().items():
            if isinstance(val, types.ModuleType):
                modulesList.append(val.__name__)
        return modulesList

    import pip
    installed_packages = sorted([ i.key for i in pip.get_installed_distributions() ])
    modules = sorted(imports())
    for module_name in modules:
        module = sys.modules[module_name]
        if module_name.lower() in installed_packages :
            try : moduleVersion = module.__version__
            except : moduleVersion = '.'.join( map(str, module.VERSION) )
            print( "=> Imported %s version %s" % (module_name , moduleVersion) )

如果我运行此脚本,python会显示:

=> Imported IPython version 6.0.0
=> Imported numpy version 1.13.1
=> Imported pandas version 0.20.2

而不是我期望的,这是以下内容:

=> Imported IPython version 6.0.0
=> Imported numpy version 1.13.1
=> Imported pandas version 0.20.2
=> Imported scipy version 0.19.0
=> Imported termcolor version 1.1.0

你能帮忙吗?

1 个答案:

答案 0 :(得分:1)

因此,我通过运行代码确定了两件事。由于以下行,IPython没有得到匹配:

if module_name in installed_packages :

当您检查'IPython'时,installed_pa​​ckages将其显示为'ipython'。

第二件事是:

modules = sorted(imports())

我不确定为什么但是termcolor没有出现

from termcolor import cprint

但是

import termcolor

不完全确定该怎么做。

编辑:

def imports():
modulesList = []
for name, val in globals().items():
    if isinstance(val, types.ModuleType):
        modulesList.append(val.__name__)
    elif isinstance(val, types.FunctionType):
        modulesList.append(sys.modules[val.__module__].__name__)
return modulesList

那应该是你的termcolor。