Python Development Workflow for Humans.
—
Virtual environment operations including package installation, version checking, and environment activation. The Environment class manages Python interpreters, installed packages, and provides context management for working within virtual environments.
Create and initialize Environment instances for managing virtual environments.
class Environment:
def __init__(self, prefix=None, python=None, is_venv=False,
base_working_set=None, pipfile=None, sources=None, project=None):
"""
Initialize an Environment instance.
Parameters:
prefix (str|Path, optional): Environment prefix path
python (str, optional): Python executable path
is_venv (bool): Whether this is a virtual environment
base_working_set (WorkingSet, optional): Base package working set
pipfile (dict, optional): Pipfile data
sources (list, optional): Package sources
project (Project, optional): Associated project instance
"""Usage examples:
from pipenv.environment import Environment
from pathlib import Path
# Create environment instance
env_path = Path("/path/to/venv")
env = Environment(prefix=env_path)
# Create with specific Python
env = Environment(prefix=env_path, python="/usr/bin/python3.9")
# Create for existing virtualenv
env = Environment(prefix=env_path, is_venv=True)Access environment metadata and configuration.
class Environment:
# Core properties
python: str # Python executable path
prefix: Path # Environment prefix path
python_version: str # Python version string
sys_path: list[str] # Python sys.path entries
base_paths: dict[str, str] # Environment base paths
# Environment state
is_venv: bool # Is virtual environment
sources: list # Package sources
pipfile: dict # Associated Pipfile dataUsage examples:
env = Environment(prefix="/path/to/venv")
# Access environment information
print(f"Python executable: {env.python}")
print(f"Python version: {env.python_version}")
print(f"Environment prefix: {env.prefix}")
print(f"Is virtual environment: {env.is_venv}")
# Check Python paths
print(f"Python sys.path: {env.sys_path}")
print(f"Base paths: {env.base_paths}")
# Access configuration
print(f"Package sources: {env.sources}")Query installed packages and their metadata.
class Environment:
def get_installed_packages(self):
"""
Get list of installed packages in environment.
Returns:
list[Distribution]: List of installed package distributions
"""
def get_outdated_packages(self, pre=False):
"""
Get packages that have newer versions available.
Parameters:
pre (bool): Include pre-release versions
Returns:
list: List of outdated package specifications
"""
def is_installed(self, pkgname):
"""
Check if a package is installed in the environment.
Parameters:
pkgname (str): Package name to check
Returns:
bool: True if package is installed
"""
def is_satisfied(self, req):
"""
Check if an install requirement is satisfied.
Parameters:
req (InstallRequirement): Requirement to check
Returns:
bool: True if requirement is satisfied
"""Usage examples:
from pip._internal.req import InstallRequirement
env = Environment(prefix="/path/to/venv")
# Get all installed packages
installed = env.get_installed_packages()
for pkg in installed:
print(f"{pkg.project_name}: {pkg.version}")
# Check for outdated packages
outdated = env.get_outdated_packages()
print(f"Outdated packages: {[pkg.project_name for pkg in outdated]}")
# Include pre-releases
outdated_pre = env.get_outdated_packages(pre=True)
# Check specific package installation
is_requests_installed = env.is_installed("requests")
print(f"Requests installed: {is_requests_installed}")
# Check requirement satisfaction
req = InstallRequirement.from_line("requests>=2.25.0")
is_satisfied = env.is_satisfied(req)
print(f"Requirement satisfied: {is_satisfied}")Context manager for activating environments.
class Environment:
def activated(self):
"""
Context manager for activating the environment.
Returns:
ContextManager: Context manager that activates environment
"""Usage examples:
import subprocess
import os
env = Environment(prefix="/path/to/venv")
# Use environment context manager
with env.activated():
# Environment is now activated
# Python executable points to virtual environment
result = subprocess.run(["python", "--version"], capture_output=True, text=True)
print(f"Active Python: {result.stdout.strip()}")
# Environment variables are set
print(f"VIRTUAL_ENV: {os.environ.get('VIRTUAL_ENV')}")
print(f"PATH: {os.environ.get('PATH')}")
# Outside context, original environment is restored
print("Environment deactivated")Access and validate Python executables.
class Environment:
def python_info(self):
"""
Get detailed Python interpreter information.
Returns:
dict: Python interpreter metadata
"""
def python_implementation(self):
"""
Get Python implementation name (CPython, PyPy, etc.).
Returns:
str: Python implementation name
"""Usage examples:
env = Environment(prefix="/path/to/venv")
# Get Python information
python_info = env.python_info()
print(f"Python info: {python_info}")
# Get implementation
implementation = env.python_implementation()
print(f"Python implementation: {implementation}") # e.g., "CPython"
# Access version details
version_info = python_info.get("version_info", {})
print(f"Python version: {version_info}")Handle path operations within the environment.
class Environment:
def script_path(self, script_name):
"""
Get path to script in environment bin directory.
Parameters:
script_name (str): Name of script
Returns:
Path: Path to script executable
"""
def site_packages_path(self):
"""
Get path to site-packages directory.
Returns:
Path: Path to site-packages
"""Usage examples:
env = Environment(prefix="/path/to/venv")
# Get script paths
pip_path = env.script_path("pip")
python_path = env.script_path("python")
print(f"Pip executable: {pip_path}")
print(f"Python executable: {python_path}")
# Get site-packages location
site_packages = env.site_packages_path()
print(f"Site-packages: {site_packages}")
# Check if scripts exist
if pip_path.exists():
print("Pip is available in environment")Working with environments in different contexts.
from pipenv.project import Project
# Get environment through project
project = Project()
env = project.get_environment()
print(f"Project environment: {env.prefix}")
print(f"Python version: {env.python_version}")
# Use project environment
with env.activated():
installed = env.get_installed_packages()
for pkg in installed:
if pkg.project_name in project.packages:
print(f"Project package: {pkg.project_name} {pkg.version}")from pipenv.environment import Environment
import subprocess
# Create standalone environment
env = Environment(prefix="/path/to/standalone/venv")
# Activate and run commands
with env.activated():
# Install package
subprocess.run(["pip", "install", "requests"], check=True)
# Verify installation
if env.is_installed("requests"):
print("Requests successfully installed")
# Run Python code
result = subprocess.run([
"python", "-c", "import requests; print(requests.__version__)"
], capture_output=True, text=True)
print(f"Requests version: {result.stdout.strip()}")# Compare environments
env1 = Environment(prefix="/path/to/venv1")
env2 = Environment(prefix="/path/to/venv2")
# Compare installed packages
packages1 = {pkg.project_name: pkg.version for pkg in env1.get_installed_packages()}
packages2 = {pkg.project_name: pkg.version for pkg in env2.get_installed_packages()}
# Find differences
only_in_env1 = set(packages1.keys()) - set(packages2.keys())
only_in_env2 = set(packages2.keys()) - set(packages1.keys())
different_versions = {
pkg for pkg in packages1
if pkg in packages2 and packages1[pkg] != packages2[pkg]
}
print(f"Only in env1: {only_in_env1}")
print(f"Only in env2: {only_in_env2}")
print(f"Different versions: {different_versions}")Handle environment-related errors appropriately.
from pipenv.environment import Environment
from pipenv.exceptions import PipenvException
try:
env = Environment(prefix="/nonexistent/path")
with env.activated():
packages = env.get_installed_packages()
except PipenvException as e:
print(f"Environment error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")from pipenv.environment import Environment
from pathlib import Path
import subprocess
# Create custom environment
venv_path = Path.home() / "my_custom_env"
# Create virtual environment
subprocess.run(["python", "-m", "venv", str(venv_path)], check=True)
# Initialize Environment instance
env = Environment(prefix=venv_path, is_venv=True)
# Verify setup
with env.activated():
print(f"Environment active: {env.python}")
print(f"Site packages: {env.site_packages_path()}")import time
from pipenv.environment import Environment
env = Environment(prefix="/path/to/venv")
def monitor_packages():
"""Monitor package changes in environment."""
last_packages = set()
while True:
current_packages = {
pkg.project_name for pkg in env.get_installed_packages()
}
if current_packages != last_packages:
added = current_packages - last_packages
removed = last_packages - current_packages
if added:
print(f"Added packages: {added}")
if removed:
print(f"Removed packages: {removed}")
last_packages = current_packages
time.sleep(5) # Check every 5 seconds
# monitor_packages() # Uncomment to runInstall with Tessl CLI
npx tessl i tessl/pypi-pipenv