在我的脚本中,我以这种方式导入了 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_packages 将其显示为“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/