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

2024-03-29 15:34:52 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的脚本中,我以这种方式导入了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

你能帮忙吗?你知道吗


Tags: installednameinimportnumpy脚本modulespandas
1条回答
网友
1楼 · 发布于 2024-03-29 15:34:52

所以有两件事我决定运行你的代码。IPython没有匹配是因为线路:

if module_name in installed_packages :

当您检查“ipython”时,已安装的\u包将其显示为“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

那应该会让你变的有颜色。你知道吗

相关问题 更多 >