如何使用 Python 3.7 或更新版本查看 Jupyter Lab 中所有已安装的 Python 模块(如 pip freeze)?

新手上路,请多包涵

我正在寻找一种方法来从 Jupyterlab 笔记本中 获取 所有已安装/可导入的 python 模块 的列表。

在命令行中,我可以通过运行来获取列表

py -3 -m pip freeze

(或者)

 pip freeze

在 Jupyterlab 控制台中,运行 pip freeze 返回

The following command must be run outside of the IPython shell:

    $ pip freeze

The Python package manager (pip) can only be used from outside of IPython.
Please reissue the `pip` command in a separate terminal or command prompt.

See the Python documentation for more information on how to install packages:

https://docs.python.org/3/installing/

对于旧版本的 pip,可以导入 pip 并从笔记本中获取列表。

命令是

help('modules')

这现在给出警告并且不返回任何内容。

 c:\python37\lib\site-packages\IPython\kernel__init__.py:13: ShimWarning: The `IPython.kernel` package has been deprecated since IPython 4.0.You should import from ipykernel or jupyter_client instead.
  "You should import from ipykernel or jupyter_client instead.", ShimWarning)

10 年前的 stackoverflow 解决方案,例如 如何获取本地安装的 Python 模块列表? 也不再工作。

有没有正确的方法来做到这一点(不使用子进程 hack 或将 pip 作为外部程序运行,如“!pip”)

原文由 576i 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 813
2 个回答
import pip._internal.operations.freeze
_ = pip._internal.operations.freeze.get_installed_distributions()
print(sorted(["%s==%s" % (i.key, i.version) for i in _])[:10])
['absl-py==0.7.1',
 'aiml==0.9.2',
 'aio-utils==0.0.1',
 'aiocache==0.10.1',
 'aiocontextvars==0.2.2',
 'aiocqhttp==0.6.7',
 'aiodns==2.0.0',
 'aiofiles==0.4.0',
 'aiohttp-proxy==0.1.1',
 'aiohttp==3.6.2']

这至少适用于 Python 3.6 和 3.7(ipython, pip.version :’20.0.1’)的 Win10。我查看了 Lib\site-packages\pip 中的源代码。

原文由 mikey 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以对结果运行以下代码段。

 !pip list

原文由 amkr 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题