如何列出所有使用 venv 创建的虚拟环境?

How can I list all the virtual environments created with venv?

刚刚有人问我如何列出使用 venv 创建的所有虚拟环境。

我只能想到搜索 pyvenv.cfg 个文件来找到它们。类似于:

from pathlib import Path

venv_list = [str(p.parent) for p in Path.home().rglob('pyvenv.cfg')]

这可能包括一些误报。有没有更好的方法来列出使用 venv 创建的所有虚拟环境?

注意:问题具体是关于 venv不是 Anaconda、virtualenv 等

在 Linux/macOS 这应该得到大部分

find ~ -d -name "site-packages" 2>/dev/null

正在您家下寻找名为 "site-packages" 的目录,venv 将其 pip 安装的东西放在那里。 /dev/null 位减少了您无权查看的事情的喋喋不休。

或者您可以查看特定预期文件的细节。例如,activate 的内容是 nondestructive。然后你需要寻找一个匹配 venv 但不匹配 anaconda 和其他模式的模式。

find ~ -type f -name "activate" -exec egrep -l nondestructive /dev/null {} \; 2>/dev/null

标准库venv 不跟踪任何创建的虚拟环境。因此,列出所有这些的唯一可能是在您的硬盘驱动器中搜索满足特定条件的文件夹。

PEP 405 gives quite good listing about what should be included in a folder so that it is a virtual environment. Also this blog post 很好地解释了虚拟环境内部的一部分。虚拟环境的定义是

A Python virtual environment in its simplest form would consist of nothing more than a copy or symlink of the Python binary accompanied by a pyvenv.cfg file and a site-packages directory. (PEP 405)

总而言之,您必须在硬盘驱动器中搜索以下文件夹:

Linux / macOS

  • pyvenv.cfghome 键*
  • bin/python3bin/python
  • lib/<python-version>/site-packages/,其中 <python-version> 例如 python3.3
  • 可选:如果使用 venv 创建,还具有 bin/activate (source). A folder is considered virtual environment even if this would be lacking. (PEP 405)

Windows

  • pyvenv.cfghome 键*
  • Script/python.exe
  • lib/<python-version>/site-packages/,其中 <python-version> 例如 python3.3
  • 可选:如果使用 venv 创建,还有 Scripts/activate.batScripts/Activate.ps1 (source). A folder is considered virtual environment even if these would be lacking. (PEP 405)

* pyvenv.cfg

pyvenv.cfg 实际上可以位于 python 可执行文件之上的同一文件夹或子文件夹中。属于虚拟环境的 pyvenv.cfg 必须有 home = <home> 行,其中 <home> 是包含用于创建虚拟环境的 Python 可执行文件的目录。 (PEP 405).