Python dependency management and packaging made easy.
—
Virtual environment creation, management, and execution. Handles Python interpreter selection and isolated execution environments for project dependencies and development workflows.
Central management system for creating, discovering, and managing virtual environments with automatic Python version detection and environment isolation.
class EnvManager:
"""
Virtual environment manager for Poetry projects.
Handles creation, discovery, and management of virtual environments
with support for different Python versions and environment types.
"""
def __init__(self, poetry_file: Path):
"""
Initialize environment manager.
Args:
poetry_file: Path to pyproject.toml file
"""
def create_venv(self, python: str = None, force: bool = False) -> VirtualEnv:
"""
Create virtual environment for project.
Args:
python: Python executable path or version
force: Force recreation if environment exists
Returns:
VirtualEnv instance
Raises:
EnvError: If environment creation fails
"""
def get_system_env(self) -> SystemEnv:
"""
Get system environment representation.
Returns:
SystemEnv instance for current Python
"""
def list_venvs(self) -> list[VirtualEnv]:
"""
List available virtual environments for project.
Returns:
List of available virtual environments
"""
def remove_venv(self, env: str = None) -> None:
"""
Remove virtual environment.
Args:
env: Environment name or path (default: project environment)
Raises:
EnvError: If removal fails
"""
def activate(self, env: Env) -> None:
"""
Activate virtual environment.
Args:
env: Environment to activate
"""
def deactivate(self) -> None:
"""Deactivate current virtual environment."""from poetry.utils.env import EnvManager
from pathlib import Path
# Create environment manager
env_manager = EnvManager(Path("/path/to/project/pyproject.toml"))
# Create virtual environment
venv = env_manager.create_venv()
print(f"Created environment: {venv.path}")
# List available environments
available_envs = env_manager.list_venvs()
for env in available_envs:
print(f"Environment: {env.path}")
# Get system environment
system_env = env_manager.get_system_env()
print(f"System Python: {system_env.python}")
# Create environment with specific Python version
python_env = env_manager.create_venv(python="python3.11")Representation and management of isolated Python environments with package installation and command execution capabilities.
class VirtualEnv(Env):
"""
Virtual environment implementation.
Provides isolated Python environment with package management
and command execution capabilities.
"""
def __init__(self, path: Path, base_python: Path = None):
"""
Initialize virtual environment.
Args:
path: Path to virtual environment
base_python: Base Python interpreter path
"""
@property
def python(self) -> str:
"""Path to Python executable in environment."""
@property
def pip(self) -> str:
"""Path to pip executable in environment."""
@property
def site_packages(self) -> Path:
"""Path to site-packages directory."""
@property
def is_venv(self) -> bool:
"""Always True for virtual environments."""
def execute(self, *args, **kwargs):
"""
Execute command in virtual environment.
Args:
*args: Command and arguments
**kwargs: Execution options
Returns:
Command execution result
Raises:
EnvCommandError: If command execution fails
"""
def install_package(self, package: str, upgrade: bool = False) -> None:
"""
Install package in virtual environment.
Args:
package: Package specification
upgrade: Whether to upgrade if already installed
Raises:
EnvError: If installation fails
"""
def uninstall_package(self, package: str) -> None:
"""
Uninstall package from virtual environment.
Args:
package: Package name
Raises:
EnvError: If uninstallation fails
"""
def get_installed_packages(self) -> list:
"""
Get list of installed packages.
Returns:
List of installed package information
"""from poetry.utils.env import EnvManager
from pathlib import Path
# Create virtual environment
env_manager = EnvManager(Path("/path/to/project/pyproject.toml"))
venv = env_manager.create_venv()
# Execute commands in environment
result = venv.execute("python", "-c", "import sys; print(sys.version)")
print(f"Python version: {result}")
# Install packages
venv.install_package("requests>=2.25.0")
venv.install_package("pytest[dev]", upgrade=True)
# Get installed packages
installed = venv.get_installed_packages()
for package in installed:
print(f"Installed: {package['name']} {package['version']}")
# Uninstall package
venv.uninstall_package("requests")Representation of the system Python environment for non-isolated execution.
class SystemEnv(Env):
"""
System environment implementation.
Represents the system Python interpreter without isolation,
useful for global package access and system-wide operations.
"""
@property
def python(self) -> str:
"""Path to system Python executable."""
@property
def is_venv(self) -> bool:
"""Always False for system environments."""
def execute(self, *args, **kwargs):
"""
Execute command in system environment.
Args:
*args: Command and arguments
**kwargs: Execution options
Returns:
Command execution result
"""
@classmethod
def from_python(cls, python: str) -> "SystemEnv":
"""
Create system environment from Python executable.
Args:
python: Path to Python executable
Returns:
SystemEnv instance
"""Generic environment wrapper for custom Python interpreters and environments.
class GenericEnv(Env):
"""
Generic environment wrapper.
Provides environment interface for custom Python interpreters
and non-standard environment configurations.
"""
def __init__(self, path: Path, is_venv: bool = False):
"""
Initialize generic environment.
Args:
path: Path to Python executable
is_venv: Whether this is a virtual environment
"""
@property
def python(self) -> str:
"""Path to Python executable."""
@property
def is_venv(self) -> bool:
"""Whether this is a virtual environment."""Helper functions for environment creation and management.
def ephemeral_environment() -> Env:
"""
Create temporary environment for isolated operations.
Returns:
Temporary environment instance
"""
def build_environment(poetry: Poetry, env: Env, io) -> Env:
"""
Create build environment for package building.
Args:
poetry: Poetry instance
env: Base environment
io: IO interface
Returns:
Build environment with necessary dependencies
"""
def get_python_version(python_path: str) -> tuple:
"""
Get Python version from executable.
Args:
python_path: Path to Python executable
Returns:
Version tuple (major, minor, micro)
"""
def find_python_versions() -> list[str]:
"""
Find available Python versions on system.
Returns:
List of Python executable paths
"""from poetry.utils.env import (
ephemeral_environment,
build_environment,
find_python_versions
)
from poetry.factory import Factory
# Create ephemeral environment
temp_env = ephemeral_environment()
result = temp_env.execute("python", "-c", "print('Hello from temp env')")
# Find available Python versions
python_versions = find_python_versions()
for python in python_versions:
print(f"Available Python: {python}")
# Create build environment
poetry = Factory().create_poetry()
env_manager = EnvManager(poetry.file.parent)
base_env = env_manager.get_system_env()
build_env = build_environment(poetry, base_env, io=None)
print(f"Build environment: {build_env.python}")Testing utilities for environment operations.
class MockEnv(Env):
"""
Mock environment for testing.
Provides fake environment implementation for testing
without creating actual virtual environments.
"""
def __init__(self, name: str = "mock-env", python_version: str = "3.9.0"):
"""
Initialize mock environment.
Args:
name: Environment name
python_version: Simulated Python version
"""
def execute(self, *args, **kwargs):
"""Mock command execution."""
@property
def python(self) -> str:
"""Mock Python executable path."""
class NullEnv(Env):
"""
Null environment implementation.
No-op environment for cases where environment
operations should be disabled or ignored.
"""
def execute(self, *args, **kwargs):
"""No-op command execution."""from poetry.utils.env import EnvManager
from poetry.config.config import Config
def configure_project_environment(project_path):
"""Configure environment based on project settings."""
config = Config.create()
# Configure virtual environment settings
if config.get("virtualenvs.in-project"):
venv_path = project_path / ".venv"
else:
venv_path = config.virtualenvs_path / "project-env"
env_manager = EnvManager(project_path / "pyproject.toml")
# Create environment with preferred Python
if config.get("virtualenvs.prefer-active-python"):
python = sys.executable
else:
python = None
venv = env_manager.create_venv(python=python)
return venvfrom contextlib import contextmanager
from poetry.utils.env import EnvManager
@contextmanager
def activated_environment(project_path):
"""Context manager for environment activation."""
env_manager = EnvManager(project_path / "pyproject.toml")
venv = env_manager.create_venv()
env_manager.activate(venv)
try:
yield venv
finally:
env_manager.deactivate()
# Usage
with activated_environment(Path("/path/to/project")) as env:
result = env.execute("python", "-c", "import sys; print(sys.executable)")Environment management exceptions and error conditions:
class EnvError(Exception):
"""Base environment error."""
class EnvCommandError(EnvError):
"""Command execution errors in environments."""
class IncorrectEnvError(EnvError):
"""Incorrect environment configuration or state."""
class PythonVersionNotFoundError(EnvError):
"""Requested Python version not available."""
class VirtualEnvCreationError(EnvError):
"""Virtual environment creation failures."""Common environment errors:
Install with Tessl CLI
npx tessl i tessl/pypi-poetry