CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pipdeptree

Command line utility to show dependency tree of packages.

Pending
Overview
Eval results
Files

environment-detection.mddocs/

Environment Detection

Automatically detects and configures for virtual environments including venv, virtualenv, conda, and Poetry with robust path resolution and interpreter discovery.

Capabilities

Main Detection Function

Primary function for automatically detecting active virtual environments.

def detect_active_interpreter() -> str:
    """
    Attempt to detect a venv, virtualenv, poetry, or conda environment.
    
    Tries multiple detection methods in order:
    1. venv/virtualenv (via VIRTUAL_ENV environment variable)
    2. conda (via CONDA_PREFIX environment variable)  
    3. Poetry (via poetry CLI command)
    
    Returns:
    Path to the detected Python interpreter
    
    Raises:
    SystemExit: If unable to detect any virtual environment
    """

Individual Detection Functions

Specific detection methods for different environment types.

def detect_venv_or_virtualenv_interpreter() -> Path | None:
    """
    Detect venv or virtualenv using VIRTUAL_ENV environment variable.
    
    Both venv (Python 3.3+) and virtualenv set the VIRTUAL_ENV variable
    when activated, pointing to the environment root directory.
    
    Returns:
    Path to Python interpreter in the virtual environment, or None if not detected
    """

def detect_conda_env_interpreter() -> Path | None:
    """
    Detect conda environment using CONDA_PREFIX environment variable.
    
    Conda sets CONDA_PREFIX to the active environment path when activated.
    Handles platform differences in interpreter location.
    
    Returns:
    Path to Python interpreter in conda environment, or None if not detected
    """

def detect_poetry_env_interpreter() -> Path | None:
    """
    Detect Poetry environment by executing 'poetry env info --executable'.
    
    Poetry doesn't set environment variables like other tools, so we query
    the Poetry CLI directly to get the active interpreter path.
    
    Returns:
    Path to Python interpreter in Poetry environment, or None if not detected
    """

Utility Functions

Helper functions for path and platform handling.

def determine_bin_dir() -> str:
    """
    Determine the correct binary directory name for the current platform.
    
    Returns:
    'Scripts' on Windows, 'bin' on POSIX systems
    """

def determine_interpreter_file_name() -> str | None:
    """
    Determine the correct Python interpreter filename for the platform.
    
    Handles different Python implementations and platform-specific extensions.
    
    Returns:
    Interpreter filename ('python', 'python.exe', 'pypy', 'pypy.exe', etc.)
    or None if implementation not recognized
    """

Usage Examples

Basic Environment Detection

from pipdeptree._detect_env import detect_active_interpreter
from pipdeptree._discovery import get_installed_distributions

try:
    # Auto-detect current virtual environment
    interpreter = detect_active_interpreter()
    print(f"Detected interpreter: {interpreter}")
    
    # Use detected interpreter for package discovery
    packages = get_installed_distributions(interpreter=interpreter)
    print(f"Found {len(packages)} packages in environment")
    
except SystemExit:
    print("No virtual environment detected")
    # Fall back to system Python
    packages = get_installed_distributions()

Manual Detection Methods

from pipdeptree._detect_env import (
    detect_venv_or_virtualenv_interpreter,
    detect_conda_env_interpreter, 
    detect_poetry_env_interpreter
)

# Try each detection method individually
venv_path = detect_venv_or_virtualenv_interpreter()
if venv_path:
    print(f"Found venv/virtualenv: {venv_path}")

conda_path = detect_conda_env_interpreter()
if conda_path:
    print(f"Found conda environment: {conda_path}")

poetry_path = detect_poetry_env_interpreter()
if poetry_path:
    print(f"Found Poetry environment: {poetry_path}")

Integration with CLI

from pipdeptree._cli import get_options
from pipdeptree._detect_env import detect_active_interpreter

# CLI automatically uses environment detection when --python auto is specified
options = get_options(['--python', 'auto'])

# This triggers environment detection internally:
if options.python == "auto":
    resolved_path = detect_active_interpreter()
    options.python = resolved_path
    print(f"Resolved python: {resolved_path}")

Environment Types Supported

venv (Python 3.3+)

Built-in virtual environment support using the venv module:

python -m venv myenv
source myenv/bin/activate  # Linux/Mac
# or myenv\Scripts\activate  # Windows

# Detection uses VIRTUAL_ENV environment variable
echo $VIRTUAL_ENV  # /path/to/myenv

Detection logic:

  • Checks VIRTUAL_ENV environment variable
  • Appends appropriate bin/ or Scripts/ directory
  • Adds correct interpreter filename with platform extension

virtualenv

Third-party virtual environment tool with broader Python version support:

pip install virtualenv
virtualenv myenv
source myenv/bin/activate

# Also sets VIRTUAL_ENV like venv
echo $VIRTUAL_ENV  # /path/to/myenv

Uses the same detection logic as venv since both tools set VIRTUAL_ENV.

conda/mamba Environments

Anaconda/Miniconda/Mamba package and environment management:

conda create -n myenv python=3.9
conda activate myenv

# Detection uses CONDA_PREFIX environment variable
echo $CONDA_PREFIX  # /path/to/miniconda3/envs/myenv

Detection logic:

  • Checks CONDA_PREFIX environment variable
  • On POSIX: interpreter in bin/ subdirectory
  • On Windows: interpreter in root directory
  • Handles different Python implementations (CPython, PyPy)

Poetry Environments

Poetry dependency management with automatic virtual environments:

poetry install
poetry shell

# Poetry doesn't set environment variables
# Detection queries Poetry CLI directly
poetry env info --executable

Detection logic:

  • Executes poetry env info --executable command
  • Captures stdout containing interpreter path
  • Returns None if Poetry not available or command fails
  • Handles all Poetry configuration methods (in-project, cached, etc.)

Platform Handling

Directory Structure Differences

POSIX (Linux, macOS, etc.):

venv/
├── bin/
│   ├── python
│   └── activate
└── lib/python3.x/site-packages/

Windows:

venv/
├── Scripts/
│   ├── python.exe
│   └── activate.bat
└── Lib/site-packages/

Python Implementation Support

Detects different Python implementations:

  • CPython: python / python.exe
  • PyPy: pypy / pypy.exe
  • Other implementations: Returns None (not supported)

Error Handling

The detection system gracefully handles various error conditions:

# Environment variable not set
if not os.environ.get("VIRTUAL_ENV"):
    return None

# Interpreter file doesn't exist
if not interpreter_path.exists():
    return None  # Detection continues with next method

# Poetry command fails
try:
    result = subprocess.run(["poetry", "env", "info", "--executable"], ...)
except Exception:
    return None  # Poetry not available or failed

Integration Points

CLI Integration

The --python auto option triggers automatic detection:

pipdeptree --python auto
# (resolved python: /path/to/detected/interpreter)

Discovery Integration

Environment detection integrates with package discovery:

# Auto-detection in get_installed_distributions
if interpreter_path != sys.executable:
    # Query the detected interpreter for its packages
    computed_paths = query_interpreter_for_paths(interpreter_path)

Error Messages

Clear error reporting when detection fails:

Unable to detect virtual environment.

The detection system exits with code 1 when no environment is found, allowing users to fall back to explicit interpreter specification.

Install with Tessl CLI

npx tessl i tessl/pypi-pipdeptree

docs

cli-interface.md

data-models.md

environment-detection.md

index.md

output-rendering.md

package-discovery.md

validation.md

warning-system.md

tile.json