or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli.mdconfiguration.mdenvironment.mdexceptions.mdindex.mdproject.mdroutines.mdutilities.md

environment.mddocs/

0

# Environment Management

1

2

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.

3

4

## Capabilities

5

6

### Environment Initialization

7

8

Create and initialize Environment instances for managing virtual environments.

9

10

```python { .api }

11

class Environment:

12

def __init__(self, prefix=None, python=None, is_venv=False,

13

base_working_set=None, pipfile=None, sources=None, project=None):

14

"""

15

Initialize an Environment instance.

16

17

Parameters:

18

prefix (str|Path, optional): Environment prefix path

19

python (str, optional): Python executable path

20

is_venv (bool): Whether this is a virtual environment

21

base_working_set (WorkingSet, optional): Base package working set

22

pipfile (dict, optional): Pipfile data

23

sources (list, optional): Package sources

24

project (Project, optional): Associated project instance

25

"""

26

```

27

28

Usage examples:

29

```python

30

from pipenv.environment import Environment

31

from pathlib import Path

32

33

# Create environment instance

34

env_path = Path("/path/to/venv")

35

env = Environment(prefix=env_path)

36

37

# Create with specific Python

38

env = Environment(prefix=env_path, python="/usr/bin/python3.9")

39

40

# Create for existing virtualenv

41

env = Environment(prefix=env_path, is_venv=True)

42

```

43

44

### Environment Properties

45

46

Access environment metadata and configuration.

47

48

```python { .api }

49

class Environment:

50

# Core properties

51

python: str # Python executable path

52

prefix: Path # Environment prefix path

53

python_version: str # Python version string

54

sys_path: list[str] # Python sys.path entries

55

base_paths: dict[str, str] # Environment base paths

56

57

# Environment state

58

is_venv: bool # Is virtual environment

59

sources: list # Package sources

60

pipfile: dict # Associated Pipfile data

61

```

62

63

Usage examples:

64

```python

65

env = Environment(prefix="/path/to/venv")

66

67

# Access environment information

68

print(f"Python executable: {env.python}")

69

print(f"Python version: {env.python_version}")

70

print(f"Environment prefix: {env.prefix}")

71

print(f"Is virtual environment: {env.is_venv}")

72

73

# Check Python paths

74

print(f"Python sys.path: {env.sys_path}")

75

print(f"Base paths: {env.base_paths}")

76

77

# Access configuration

78

print(f"Package sources: {env.sources}")

79

```

80

81

### Package Inspection

82

83

Query installed packages and their metadata.

84

85

```python { .api }

86

class Environment:

87

def get_installed_packages(self):

88

"""

89

Get list of installed packages in environment.

90

91

Returns:

92

list[Distribution]: List of installed package distributions

93

"""

94

95

def get_outdated_packages(self, pre=False):

96

"""

97

Get packages that have newer versions available.

98

99

Parameters:

100

pre (bool): Include pre-release versions

101

102

Returns:

103

list: List of outdated package specifications

104

"""

105

106

def is_installed(self, pkgname):

107

"""

108

Check if a package is installed in the environment.

109

110

Parameters:

111

pkgname (str): Package name to check

112

113

Returns:

114

bool: True if package is installed

115

"""

116

117

def is_satisfied(self, req):

118

"""

119

Check if an install requirement is satisfied.

120

121

Parameters:

122

req (InstallRequirement): Requirement to check

123

124

Returns:

125

bool: True if requirement is satisfied

126

"""

127

```

128

129

Usage examples:

130

```python

131

from pip._internal.req import InstallRequirement

132

133

env = Environment(prefix="/path/to/venv")

134

135

# Get all installed packages

136

installed = env.get_installed_packages()

137

for pkg in installed:

138

print(f"{pkg.project_name}: {pkg.version}")

139

140

# Check for outdated packages

141

outdated = env.get_outdated_packages()

142

print(f"Outdated packages: {[pkg.project_name for pkg in outdated]}")

143

144

# Include pre-releases

145

outdated_pre = env.get_outdated_packages(pre=True)

146

147

# Check specific package installation

148

is_requests_installed = env.is_installed("requests")

149

print(f"Requests installed: {is_requests_installed}")

150

151

# Check requirement satisfaction

152

req = InstallRequirement.from_line("requests>=2.25.0")

153

is_satisfied = env.is_satisfied(req)

154

print(f"Requirement satisfied: {is_satisfied}")

155

```

156

157

### Environment Activation

158

159

Context manager for activating environments.

160

161

```python { .api }

162

class Environment:

163

def activated(self):

164

"""

165

Context manager for activating the environment.

166

167

Returns:

168

ContextManager: Context manager that activates environment

169

"""

170

```

171

172

Usage examples:

173

```python

174

import subprocess

175

import os

176

177

env = Environment(prefix="/path/to/venv")

178

179

# Use environment context manager

180

with env.activated():

181

# Environment is now activated

182

# Python executable points to virtual environment

183

result = subprocess.run(["python", "--version"], capture_output=True, text=True)

184

print(f"Active Python: {result.stdout.strip()}")

185

186

# Environment variables are set

187

print(f"VIRTUAL_ENV: {os.environ.get('VIRTUAL_ENV')}")

188

print(f"PATH: {os.environ.get('PATH')}")

189

190

# Outside context, original environment is restored

191

print("Environment deactivated")

192

```

193

194

### Python Executable Management

195

196

Access and validate Python executables.

197

198

```python { .api }

199

class Environment:

200

def python_info(self):

201

"""

202

Get detailed Python interpreter information.

203

204

Returns:

205

dict: Python interpreter metadata

206

"""

207

208

def python_implementation(self):

209

"""

210

Get Python implementation name (CPython, PyPy, etc.).

211

212

Returns:

213

str: Python implementation name

214

"""

215

```

216

217

Usage examples:

218

```python

219

env = Environment(prefix="/path/to/venv")

220

221

# Get Python information

222

python_info = env.python_info()

223

print(f"Python info: {python_info}")

224

225

# Get implementation

226

implementation = env.python_implementation()

227

print(f"Python implementation: {implementation}") # e.g., "CPython"

228

229

# Access version details

230

version_info = python_info.get("version_info", {})

231

print(f"Python version: {version_info}")

232

```

233

234

### Path Resolution

235

236

Handle path operations within the environment.

237

238

```python { .api }

239

class Environment:

240

def script_path(self, script_name):

241

"""

242

Get path to script in environment bin directory.

243

244

Parameters:

245

script_name (str): Name of script

246

247

Returns:

248

Path: Path to script executable

249

"""

250

251

def site_packages_path(self):

252

"""

253

Get path to site-packages directory.

254

255

Returns:

256

Path: Path to site-packages

257

"""

258

```

259

260

Usage examples:

261

```python

262

env = Environment(prefix="/path/to/venv")

263

264

# Get script paths

265

pip_path = env.script_path("pip")

266

python_path = env.script_path("python")

267

print(f"Pip executable: {pip_path}")

268

print(f"Python executable: {python_path}")

269

270

# Get site-packages location

271

site_packages = env.site_packages_path()

272

print(f"Site-packages: {site_packages}")

273

274

# Check if scripts exist

275

if pip_path.exists():

276

print("Pip is available in environment")

277

```

278

279

## Environment Context Integration

280

281

Working with environments in different contexts.

282

283

### Project Integration

284

285

```python

286

from pipenv.project import Project

287

288

# Get environment through project

289

project = Project()

290

env = project.get_environment()

291

292

print(f"Project environment: {env.prefix}")

293

print(f"Python version: {env.python_version}")

294

295

# Use project environment

296

with env.activated():

297

installed = env.get_installed_packages()

298

for pkg in installed:

299

if pkg.project_name in project.packages:

300

print(f"Project package: {pkg.project_name} {pkg.version}")

301

```

302

303

### Standalone Usage

304

305

```python

306

from pipenv.environment import Environment

307

import subprocess

308

309

# Create standalone environment

310

env = Environment(prefix="/path/to/standalone/venv")

311

312

# Activate and run commands

313

with env.activated():

314

# Install package

315

subprocess.run(["pip", "install", "requests"], check=True)

316

317

# Verify installation

318

if env.is_installed("requests"):

319

print("Requests successfully installed")

320

321

# Run Python code

322

result = subprocess.run([

323

"python", "-c", "import requests; print(requests.__version__)"

324

], capture_output=True, text=True)

325

print(f"Requests version: {result.stdout.strip()}")

326

```

327

328

### Environment Comparison

329

330

```python

331

# Compare environments

332

env1 = Environment(prefix="/path/to/venv1")

333

env2 = Environment(prefix="/path/to/venv2")

334

335

# Compare installed packages

336

packages1 = {pkg.project_name: pkg.version for pkg in env1.get_installed_packages()}

337

packages2 = {pkg.project_name: pkg.version for pkg in env2.get_installed_packages()}

338

339

# Find differences

340

only_in_env1 = set(packages1.keys()) - set(packages2.keys())

341

only_in_env2 = set(packages2.keys()) - set(packages1.keys())

342

different_versions = {

343

pkg for pkg in packages1

344

if pkg in packages2 and packages1[pkg] != packages2[pkg]

345

}

346

347

print(f"Only in env1: {only_in_env1}")

348

print(f"Only in env2: {only_in_env2}")

349

print(f"Different versions: {different_versions}")

350

```

351

352

## Error Handling

353

354

Handle environment-related errors appropriately.

355

356

```python

357

from pipenv.environment import Environment

358

from pipenv.exceptions import PipenvException

359

360

try:

361

env = Environment(prefix="/nonexistent/path")

362

with env.activated():

363

packages = env.get_installed_packages()

364

except PipenvException as e:

365

print(f"Environment error: {e}")

366

except Exception as e:

367

print(f"Unexpected error: {e}")

368

```

369

370

## Advanced Usage

371

372

### Custom Environment Creation

373

374

```python

375

from pipenv.environment import Environment

376

from pathlib import Path

377

import subprocess

378

379

# Create custom environment

380

venv_path = Path.home() / "my_custom_env"

381

382

# Create virtual environment

383

subprocess.run(["python", "-m", "venv", str(venv_path)], check=True)

384

385

# Initialize Environment instance

386

env = Environment(prefix=venv_path, is_venv=True)

387

388

# Verify setup

389

with env.activated():

390

print(f"Environment active: {env.python}")

391

print(f"Site packages: {env.site_packages_path()}")

392

```

393

394

### Environment Monitoring

395

396

```python

397

import time

398

from pipenv.environment import Environment

399

400

env = Environment(prefix="/path/to/venv")

401

402

def monitor_packages():

403

"""Monitor package changes in environment."""

404

last_packages = set()

405

406

while True:

407

current_packages = {

408

pkg.project_name for pkg in env.get_installed_packages()

409

}

410

411

if current_packages != last_packages:

412

added = current_packages - last_packages

413

removed = last_packages - current_packages

414

415

if added:

416

print(f"Added packages: {added}")

417

if removed:

418

print(f"Removed packages: {removed}")

419

420

last_packages = current_packages

421

422

time.sleep(5) # Check every 5 seconds

423

424

# monitor_packages() # Uncomment to run

425

```