2019-03-14 更新
我最终为此自己构建了一个名为 session_info 的包,以便在输出中具有更大的灵活性(例如,显示通过其他模块间接导入的模块)并可以在笔记本之外访问此功能。它可以通过pip install session-info 安装并像这样使用:
# Some sample imported modules
import math
import natsort
import pandas
import session_info
session_info.show()
它为您提供类似于
的输出
Session information:
-----
natsort 7.1.1
pandas 1.2.2
session_info 1.0.0
-----
IPython 7.23.0
jupyter_client 6.1.12
jupyter_core 4.7.1
-----
Python 3.9.2 | packaged by conda-forge | (default, Feb 21 2021, 05:02:46) [GCC 9.3.0]
Linux-5.11.13-arch1-1-x86_64-with-glibc2.33
-----
Session information updated at 2021-05-06 09:59
原答案
有一个名为version_information 的魔术包可以完成此任务。使用pip install version_information 安装。 (注意这个扩展已经有一段时间没有更新了,有一个更新的叫做watermark)
%load_ext version_information
%version_information pandas, numpy, seaborn
输出:
您也可以使用How to list imported modules? 中的解决方案和!pip freeze 完成类似的操作。
#find the names of the imported modules
import types
def imports():
for name, val in globals().items():
if isinstance(val, types.ModuleType):
yield val.__name__
#exclude all modules not listed by `!pip freeze`
excludes = ['__builtin__', 'types', 'IPython.core.shadowns', 'sys', 'os']
imported_modules = [module for module in imports() if module not in excludes]
pip_modules = !pip freeze #you could also use `!conda list` with anaconda
#print the names and versions of the imported modules
for module in pip_modules:
name, version = module.split('==')
if name in imported_modules:
print(name + '\t' + version)
输出:
pandas 0.16.2
numpy 1.9.2
seaborn 0.5.1
我不知道如何将带有导入模块的列表(例如modulenames)传递给%version_information 魔术命令(所有引号都需要删除),所以也许有人可以通过添加来改进这个答案那个信息。