There isn’t really a “one-size-fits-all” drop-in on PyPI that will magically locate every kind of venv (Poetry, Pipenv, Hatch, PDM, plain venv, virtualenv, tox, …) for you, but most tools fall into one of a few patterns:
- they create an “in-project” folder (usually named
.venv, venv, env, ENV, …)
- they live in a central cache or per-user directory (e.g. pipenv‘s
~/.local/share/virtualenvs/…)
- they expose a CLI you can shell out to (
pipenv --venv, poetry env info -p, pdm venv path, etc.)
- or you can detect any venv by walking up your directory tree looking for a
pyvenv.cfg file.
If you only need to cover e.g. Poetry + Pipenv + plain venv, you can roll your own with roughly this recipe:
import os
import subprocess
from pathlib import Path
def find_in_project_venv(root):
"""Look for .venv, venv, env, ENV in the project root."""
for name in (".venv", "venv", "env", "ENV"):
p = root / name
if (p / "pyvenv.cfg").exists():
return str(p)
return None
def find_pyvenv_cfg(start):
"""Walk up looking for ANY pyvenv.cfg."""
p = Path(start).resolve()
for parent in (p, *p.parents):
if (parent / "pyvenv.cfg").exists():
return str(parent)
return None
def pipenv_venv(project_root):
try:
out = subprocess.check_output(
["pipenv", "--venv"],
cwd=project_root,
stderr=subprocess.DEVNULL,
)
return out.decode().strip()
except Exception:
return None
def poetry_venv(project_root):
try:
out = subprocess.check_output(
["poetry", "env", "info", "-p"],
cwd=project_root,
stderr=subprocess.DEVNULL,
)
return out.decode().strip()
except Exception:
return None
def discover_venv(project_root=None):
project_root = Path(project_root or os.getcwd()).resolve()
# 1) in-project .venv folder (Poetry if in-project, or any manual venv)
venv = find_in_project_venv(project_root)
if venv:
return venv
# 2) Pipenv
venv = pipenv_venv(project_root)
if venv:
return venv
# 3) Poetry normal (outside-project)
venv = poetry_venv(project_root)
if venv:
return venv
# 4) fallback: any pyvenv.cfg up the tree
venv = find_pyvenv_cfg(project_root)
if venv:
return venv
return None
if __name__ == "__main__":
print(discover_venv())
— That little snippet will already handle:
- Poetry (in-project and external)
- Pipenv
- Any plain venv or virtualenv you created manually
If you want to cover Hatch, PDM, tox or others, you simply add the corresponding “shell out to their CLI” or “look for their config file or special folder” steps.
A few folks have bundled the above logic into small libraries, but none has really “won” as the de-facto standard yet. If you want a head start:
• Check out how the VS Code Python extension does env discovery (in its open-source repo under pythonEnvironments/).
• You can also browse the source of pipenv, poetry-core and hatch’s CLI to see exactly how they compute their venv paths.
But in practice most projects end up shipping their own 20–30 lines of “venv finder” like the one above.