0
# Environment Management
1
2
Virtual environment creation, management, and execution. Handles Python interpreter selection and isolated execution environments for project dependencies and development workflows.
3
4
## Capabilities
5
6
### Environment Manager
7
8
Central management system for creating, discovering, and managing virtual environments with automatic Python version detection and environment isolation.
9
10
```python { .api }
11
class EnvManager:
12
"""
13
Virtual environment manager for Poetry projects.
14
15
Handles creation, discovery, and management of virtual environments
16
with support for different Python versions and environment types.
17
"""
18
19
def __init__(self, poetry_file: Path):
20
"""
21
Initialize environment manager.
22
23
Args:
24
poetry_file: Path to pyproject.toml file
25
"""
26
27
def create_venv(self, python: str = None, force: bool = False) -> VirtualEnv:
28
"""
29
Create virtual environment for project.
30
31
Args:
32
python: Python executable path or version
33
force: Force recreation if environment exists
34
35
Returns:
36
VirtualEnv instance
37
38
Raises:
39
EnvError: If environment creation fails
40
"""
41
42
def get_system_env(self) -> SystemEnv:
43
"""
44
Get system environment representation.
45
46
Returns:
47
SystemEnv instance for current Python
48
"""
49
50
def list_venvs(self) -> list[VirtualEnv]:
51
"""
52
List available virtual environments for project.
53
54
Returns:
55
List of available virtual environments
56
"""
57
58
def remove_venv(self, env: str = None) -> None:
59
"""
60
Remove virtual environment.
61
62
Args:
63
env: Environment name or path (default: project environment)
64
65
Raises:
66
EnvError: If removal fails
67
"""
68
69
def activate(self, env: Env) -> None:
70
"""
71
Activate virtual environment.
72
73
Args:
74
env: Environment to activate
75
"""
76
77
def deactivate(self) -> None:
78
"""Deactivate current virtual environment."""
79
```
80
81
#### Usage Example
82
83
```python
84
from poetry.utils.env import EnvManager
85
from pathlib import Path
86
87
# Create environment manager
88
env_manager = EnvManager(Path("/path/to/project/pyproject.toml"))
89
90
# Create virtual environment
91
venv = env_manager.create_venv()
92
print(f"Created environment: {venv.path}")
93
94
# List available environments
95
available_envs = env_manager.list_venvs()
96
for env in available_envs:
97
print(f"Environment: {env.path}")
98
99
# Get system environment
100
system_env = env_manager.get_system_env()
101
print(f"System Python: {system_env.python}")
102
103
# Create environment with specific Python version
104
python_env = env_manager.create_venv(python="python3.11")
105
```
106
107
### Virtual Environment
108
109
Representation and management of isolated Python environments with package installation and command execution capabilities.
110
111
```python { .api }
112
class VirtualEnv(Env):
113
"""
114
Virtual environment implementation.
115
116
Provides isolated Python environment with package management
117
and command execution capabilities.
118
"""
119
120
def __init__(self, path: Path, base_python: Path = None):
121
"""
122
Initialize virtual environment.
123
124
Args:
125
path: Path to virtual environment
126
base_python: Base Python interpreter path
127
"""
128
129
@property
130
def python(self) -> str:
131
"""Path to Python executable in environment."""
132
133
@property
134
def pip(self) -> str:
135
"""Path to pip executable in environment."""
136
137
@property
138
def site_packages(self) -> Path:
139
"""Path to site-packages directory."""
140
141
@property
142
def is_venv(self) -> bool:
143
"""Always True for virtual environments."""
144
145
def execute(self, *args, **kwargs):
146
"""
147
Execute command in virtual environment.
148
149
Args:
150
*args: Command and arguments
151
**kwargs: Execution options
152
153
Returns:
154
Command execution result
155
156
Raises:
157
EnvCommandError: If command execution fails
158
"""
159
160
def install_package(self, package: str, upgrade: bool = False) -> None:
161
"""
162
Install package in virtual environment.
163
164
Args:
165
package: Package specification
166
upgrade: Whether to upgrade if already installed
167
168
Raises:
169
EnvError: If installation fails
170
"""
171
172
def uninstall_package(self, package: str) -> None:
173
"""
174
Uninstall package from virtual environment.
175
176
Args:
177
package: Package name
178
179
Raises:
180
EnvError: If uninstallation fails
181
"""
182
183
def get_installed_packages(self) -> list:
184
"""
185
Get list of installed packages.
186
187
Returns:
188
List of installed package information
189
"""
190
```
191
192
#### Usage Example
193
194
```python
195
from poetry.utils.env import EnvManager
196
from pathlib import Path
197
198
# Create virtual environment
199
env_manager = EnvManager(Path("/path/to/project/pyproject.toml"))
200
venv = env_manager.create_venv()
201
202
# Execute commands in environment
203
result = venv.execute("python", "-c", "import sys; print(sys.version)")
204
print(f"Python version: {result}")
205
206
# Install packages
207
venv.install_package("requests>=2.25.0")
208
venv.install_package("pytest[dev]", upgrade=True)
209
210
# Get installed packages
211
installed = venv.get_installed_packages()
212
for package in installed:
213
print(f"Installed: {package['name']} {package['version']}")
214
215
# Uninstall package
216
venv.uninstall_package("requests")
217
```
218
219
### System Environment
220
221
Representation of the system Python environment for non-isolated execution.
222
223
```python { .api }
224
class SystemEnv(Env):
225
"""
226
System environment implementation.
227
228
Represents the system Python interpreter without isolation,
229
useful for global package access and system-wide operations.
230
"""
231
232
@property
233
def python(self) -> str:
234
"""Path to system Python executable."""
235
236
@property
237
def is_venv(self) -> bool:
238
"""Always False for system environments."""
239
240
def execute(self, *args, **kwargs):
241
"""
242
Execute command in system environment.
243
244
Args:
245
*args: Command and arguments
246
**kwargs: Execution options
247
248
Returns:
249
Command execution result
250
"""
251
252
@classmethod
253
def from_python(cls, python: str) -> "SystemEnv":
254
"""
255
Create system environment from Python executable.
256
257
Args:
258
python: Path to Python executable
259
260
Returns:
261
SystemEnv instance
262
"""
263
```
264
265
### Generic Environment
266
267
Generic environment wrapper for custom Python interpreters and environments.
268
269
```python { .api }
270
class GenericEnv(Env):
271
"""
272
Generic environment wrapper.
273
274
Provides environment interface for custom Python interpreters
275
and non-standard environment configurations.
276
"""
277
278
def __init__(self, path: Path, is_venv: bool = False):
279
"""
280
Initialize generic environment.
281
282
Args:
283
path: Path to Python executable
284
is_venv: Whether this is a virtual environment
285
"""
286
287
@property
288
def python(self) -> str:
289
"""Path to Python executable."""
290
291
@property
292
def is_venv(self) -> bool:
293
"""Whether this is a virtual environment."""
294
```
295
296
### Environment Utilities
297
298
Helper functions for environment creation and management.
299
300
```python { .api }
301
def ephemeral_environment() -> Env:
302
"""
303
Create temporary environment for isolated operations.
304
305
Returns:
306
Temporary environment instance
307
"""
308
309
def build_environment(poetry: Poetry, env: Env, io) -> Env:
310
"""
311
Create build environment for package building.
312
313
Args:
314
poetry: Poetry instance
315
env: Base environment
316
io: IO interface
317
318
Returns:
319
Build environment with necessary dependencies
320
"""
321
322
def get_python_version(python_path: str) -> tuple:
323
"""
324
Get Python version from executable.
325
326
Args:
327
python_path: Path to Python executable
328
329
Returns:
330
Version tuple (major, minor, micro)
331
"""
332
333
def find_python_versions() -> list[str]:
334
"""
335
Find available Python versions on system.
336
337
Returns:
338
List of Python executable paths
339
"""
340
```
341
342
#### Usage Example
343
344
```python
345
from poetry.utils.env import (
346
ephemeral_environment,
347
build_environment,
348
find_python_versions
349
)
350
from poetry.factory import Factory
351
352
# Create ephemeral environment
353
temp_env = ephemeral_environment()
354
result = temp_env.execute("python", "-c", "print('Hello from temp env')")
355
356
# Find available Python versions
357
python_versions = find_python_versions()
358
for python in python_versions:
359
print(f"Available Python: {python}")
360
361
# Create build environment
362
poetry = Factory().create_poetry()
363
env_manager = EnvManager(poetry.file.parent)
364
base_env = env_manager.get_system_env()
365
366
build_env = build_environment(poetry, base_env, io=None)
367
print(f"Build environment: {build_env.python}")
368
```
369
370
### Environment Testing and Mocking
371
372
Testing utilities for environment operations.
373
374
```python { .api }
375
class MockEnv(Env):
376
"""
377
Mock environment for testing.
378
379
Provides fake environment implementation for testing
380
without creating actual virtual environments.
381
"""
382
383
def __init__(self, name: str = "mock-env", python_version: str = "3.9.0"):
384
"""
385
Initialize mock environment.
386
387
Args:
388
name: Environment name
389
python_version: Simulated Python version
390
"""
391
392
def execute(self, *args, **kwargs):
393
"""Mock command execution."""
394
395
@property
396
def python(self) -> str:
397
"""Mock Python executable path."""
398
399
class NullEnv(Env):
400
"""
401
Null environment implementation.
402
403
No-op environment for cases where environment
404
operations should be disabled or ignored.
405
"""
406
407
def execute(self, *args, **kwargs):
408
"""No-op command execution."""
409
```
410
411
### Advanced Environment Patterns
412
413
#### Environment Configuration
414
415
```python
416
from poetry.utils.env import EnvManager
417
from poetry.config.config import Config
418
419
def configure_project_environment(project_path):
420
"""Configure environment based on project settings."""
421
config = Config.create()
422
423
# Configure virtual environment settings
424
if config.get("virtualenvs.in-project"):
425
venv_path = project_path / ".venv"
426
else:
427
venv_path = config.virtualenvs_path / "project-env"
428
429
env_manager = EnvManager(project_path / "pyproject.toml")
430
431
# Create environment with preferred Python
432
if config.get("virtualenvs.prefer-active-python"):
433
python = sys.executable
434
else:
435
python = None
436
437
venv = env_manager.create_venv(python=python)
438
return venv
439
```
440
441
#### Environment Activation Context
442
443
```python
444
from contextlib import contextmanager
445
from poetry.utils.env import EnvManager
446
447
@contextmanager
448
def activated_environment(project_path):
449
"""Context manager for environment activation."""
450
env_manager = EnvManager(project_path / "pyproject.toml")
451
venv = env_manager.create_venv()
452
453
env_manager.activate(venv)
454
try:
455
yield venv
456
finally:
457
env_manager.deactivate()
458
459
# Usage
460
with activated_environment(Path("/path/to/project")) as env:
461
result = env.execute("python", "-c", "import sys; print(sys.executable)")
462
```
463
464
## Error Handling
465
466
Environment management exceptions and error conditions:
467
468
```python { .api }
469
class EnvError(Exception):
470
"""Base environment error."""
471
472
class EnvCommandError(EnvError):
473
"""Command execution errors in environments."""
474
475
class IncorrectEnvError(EnvError):
476
"""Incorrect environment configuration or state."""
477
478
class PythonVersionNotFoundError(EnvError):
479
"""Requested Python version not available."""
480
481
class VirtualEnvCreationError(EnvError):
482
"""Virtual environment creation failures."""
483
```
484
485
Common environment errors:
486
- Python interpreter not found or invalid
487
- Virtual environment creation failures
488
- Permission errors accessing environment directories
489
- Command execution failures in environments
490
- Environment corruption or invalid state
491
- Missing dependencies for environment operations