python : Get a complete list of external modules imported by my script and their version

标签 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

你能帮忙吗?

最佳答案

我通过运行您的代码确定了两件事。由于以下行,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。

关于 python : Get a complete list of external modules imported by my script and their version,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45861905/

相关文章:

python - 如何为现有项目自动创建新的 xcode 目标

Python 多处理池 async_apply 回调在传递参数时不起作用

python - 使用 AdamOptimizer 继续训练自定义 tf.Estimator

python - 如何在 ubuntu 上安装 python 模块 sys、os 和 getopt?

python - 尝试将 Raspberry Pi 天气数据上传到 SQL 数据库时 MySQLdb 不工作

python - 如何使用 Django 在 Bootstrap 中每行显示 2 个 span6 的缩略图?

与模块位于同一文件中的 Python 子模块

python - 如何在绝对导入中设置没有点符号的 Pypi 包 - python3

python - 在我的 python 项目中使用我自己的模块的最佳方式

python - Python中模块和类的区别