0
# Environment Creation
1
2
Core functionality for creating and configuring virtual Python environments with extensive customization options including Python interpreter selection, package isolation controls, and dependency management.
3
4
## Capabilities
5
6
### Primary Environment Creation
7
8
Creates a complete virtual Python environment with all necessary components including Python interpreter, standard library, package management tools, and activation scripts.
9
10
```python { .api }
11
def create_environment(
12
home_dir,
13
site_packages=False,
14
clear=False,
15
prompt=None,
16
search_dirs=None,
17
download=False,
18
no_setuptools=False,
19
no_pip=False,
20
no_wheel=False,
21
symlink=True
22
):
23
"""
24
Creates a new environment in home_dir.
25
26
If site_packages is true, then the global site-packages/ directory
27
will be on the path. If clear is true (default False) then the
28
environment will first be cleared.
29
30
Parameters:
31
- home_dir (str): Target directory for the virtual environment
32
- site_packages (bool): Include global site-packages in environment path
33
- clear (bool): Clear existing environment before creating new one
34
- prompt (str): Custom prompt prefix for the environment
35
- search_dirs (list): Directories to search for wheel packages
36
- download (bool): Download packages if not found locally
37
- no_setuptools (bool): Skip installing setuptools package
38
- no_pip (bool): Skip installing pip package manager
39
- no_wheel (bool): Skip installing wheel package
40
- symlink (bool): Use symlinks instead of copying files when possible
41
42
Returns:
43
None
44
45
Raises:
46
OSError: If directory creation fails
47
subprocess.CalledProcessError: If package installation fails
48
"""
49
```
50
51
**Usage Examples:**
52
53
```python
54
import virtualenv
55
56
# Create basic environment
57
virtualenv.create_environment('/path/to/myenv')
58
59
# Create environment with global packages accessible
60
virtualenv.create_environment('/path/to/myenv', site_packages=True)
61
62
# Create clean environment (removes existing first)
63
virtualenv.create_environment('/path/to/myenv', clear=True)
64
65
# Create environment without pip
66
virtualenv.create_environment('/path/to/myenv', no_pip=True)
67
68
# Create environment with custom prompt
69
virtualenv.create_environment('/path/to/myenv', prompt='myproject')
70
```
71
72
### Command Line Interface
73
74
Main entry point for command-line usage providing full option parsing and environment creation based on command-line arguments.
75
76
```python { .api }
77
def main():
78
"""
79
Command-line interface entry point for virtualenv.
80
81
Parses command-line arguments using optparse and creates virtual
82
environment based on provided options. Handles all CLI flags including
83
verbose/quiet modes, Python interpreter selection, and environment
84
configuration options.
85
86
Command-line options include:
87
- --python PYTHON_EXE: Specify Python interpreter
88
- --clear: Clear existing environment
89
- --system-site-packages: Give access to global site-packages
90
- --always-copy: Always copy files rather than symlinking
91
- --prompt PROMPT: Custom environment prompt
92
- --no-setuptools: Don't install setuptools
93
- --no-pip: Don't install pip
94
- --no-wheel: Don't install wheel
95
- -v/--verbose: Increase verbosity
96
- -q/--quiet: Decrease verbosity
97
98
Parameters:
99
Uses sys.argv for argument parsing
100
101
Returns:
102
None (exits process with appropriate exit code)
103
104
Raises:
105
SystemExit: On argument parsing errors or environment creation failures
106
"""
107
```
108
109
**Usage Examples:**
110
111
```python
112
import virtualenv
113
import sys
114
115
# Use with custom arguments
116
sys.argv = ['virtualenv', '--python=python3.8', '/path/to/myenv']
117
virtualenv.main()
118
119
# Use with current sys.argv
120
virtualenv.main()
121
```
122
123
### Python Interpreter Resolution
124
125
Resolves and validates Python interpreter paths for environment creation, handling various Python installations and versions.
126
127
```python { .api }
128
def resolve_interpreter(exe):
129
"""
130
Resolve Python interpreter path from executable name or path.
131
132
Takes a Python executable name (like 'python3.8') or path and resolves
133
it to an absolute path, validating that it's a working Python interpreter.
134
Handles platform-specific executable extensions and search paths.
135
136
Parameters:
137
- exe (str): Python executable name or path (e.g., 'python3.8', '/usr/bin/python')
138
139
Returns:
140
str: Absolute path to resolved Python interpreter
141
142
Raises:
143
RuntimeError: If interpreter cannot be found or is not executable
144
"""
145
```
146
147
**Usage Examples:**
148
149
```python
150
import virtualenv
151
152
# Resolve system Python
153
python_path = virtualenv.resolve_interpreter('python')
154
155
# Resolve specific version
156
python38_path = virtualenv.resolve_interpreter('python3.8')
157
158
# Resolve from absolute path
159
custom_path = virtualenv.resolve_interpreter('/opt/python/bin/python')
160
```
161
162
### Environment Relocation
163
164
Makes virtual environments relocatable by adjusting internal paths, useful for deployment and distribution scenarios.
165
166
```python { .api }
167
def make_environment_relocatable(home_dir):
168
"""
169
Make a virtual environment relocatable.
170
171
Modifies the virtual environment to use relative paths instead of
172
absolute paths, allowing the environment directory to be moved to
173
different locations while maintaining functionality.
174
175
Parameters:
176
- home_dir (str): Path to virtual environment directory
177
178
Returns:
179
None
180
181
Raises:
182
OSError: If environment directory doesn't exist or modification fails
183
"""
184
```
185
186
**Usage Examples:**
187
188
```python
189
import virtualenv
190
191
# Create environment then make it relocatable
192
virtualenv.create_environment('/path/to/myenv')
193
virtualenv.make_environment_relocatable('/path/to/myenv')
194
```
195
196
### Package Discovery and Installation
197
198
Functions for finding and installing wheel packages in virtual environments.
199
200
```python { .api }
201
def find_wheels(projects, search_dirs):
202
"""
203
Find wheel files for given projects.
204
205
Searches specified directories for wheel files matching the given
206
project names. Returns mapping of project names to wheel file paths.
207
208
Parameters:
209
- projects (list): List of project names to find wheels for
210
- search_dirs (list): Directories to search for wheel files
211
212
Returns:
213
dict: Mapping of project names to wheel file paths
214
Example: {'pip': '/path/to/pip-20.0.0-py2.py3-none-any.whl'}
215
216
Raises:
217
OSError: If search directories cannot be accessed
218
"""
219
```
220
221
**Usage Examples:**
222
223
```python
224
import virtualenv
225
226
# Find wheels for specific projects
227
search_dirs = ['/path/to/wheels', '/another/wheel/dir']
228
wheels = virtualenv.find_wheels(['pip', 'setuptools'], search_dirs)
229
print(f"Found wheels: {wheels}")
230
```
231
232
### Package Installation
233
234
Installs wheel packages in virtual environments with support for local search directories and package downloading.
235
236
```python { .api }
237
def install_wheel(project_names, py_executable, search_dirs=None, download=False):
238
"""
239
Install wheel packages in virtual environment.
240
241
Installs specified packages using wheel format, searching in provided
242
directories or downloading if needed. Commonly used for installing
243
setuptools, pip, and wheel in new environments.
244
245
Parameters:
246
- project_names (list): List of package names to install
247
- py_executable (str): Path to Python executable in target environment
248
- search_dirs (list, optional): Directories to search for wheel files
249
- download (bool): Download packages if not found locally
250
251
Returns:
252
None
253
254
Raises:
255
subprocess.CalledProcessError: If package installation fails
256
"""
257
```
258
259
**Usage Examples:**
260
261
```python
262
import virtualenv
263
264
# Install default packages
265
python_exe = '/path/to/myenv/bin/python'
266
virtualenv.install_wheel(['pip', 'setuptools', 'wheel'], python_exe)
267
268
# Install with custom search directories
269
search_dirs = ['/path/to/wheels']
270
virtualenv.install_wheel(['mypackage'], python_exe, search_dirs=search_dirs)
271
272
# Install with download fallback
273
virtualenv.install_wheel(['requests'], python_exe, download=True)
274
```
275
276
### Environment Component Installation
277
278
Functions for installing specific components during virtual environment setup.
279
280
```python { .api }
281
def install_distutils(home_dir):
282
"""
283
Install distutils configuration in virtual environment.
284
285
Sets up distutils configuration files and paths for proper
286
package installation behavior within the virtual environment.
287
288
Parameters:
289
- home_dir (str): Virtual environment home directory
290
291
Returns:
292
None
293
294
Raises:
295
OSError: If distutils configuration cannot be installed
296
"""
297
298
def install_activate(home_dir, bin_dir, prompt=None):
299
"""
300
Install activation scripts in virtual environment.
301
302
Creates platform-specific activation scripts (activate, activate.bat,
303
activate.ps1, etc.) that set up environment variables for using
304
the virtual environment.
305
306
Parameters:
307
- home_dir (str): Virtual environment home directory
308
- bin_dir (str): Binary/scripts directory
309
- prompt (str, optional): Custom prompt for activated environment
310
311
Returns:
312
None
313
314
Raises:
315
OSError: If activation scripts cannot be created
316
"""
317
318
def install_python_config(home_dir, bin_dir, prompt=None):
319
"""
320
Install Python configuration script in virtual environment.
321
322
Creates python-config script for querying Python configuration
323
information within the virtual environment context.
324
325
Parameters:
326
- home_dir (str): Virtual environment home directory
327
- bin_dir (str): Binary/scripts directory
328
- prompt (str, optional): Environment prompt
329
330
Returns:
331
None
332
333
Raises:
334
OSError: If python-config script cannot be created
335
"""
336
337
def install_python(home_dir, lib_dir, inc_dir, bin_dir, site_packages, clear, symlink=True):
338
"""
339
Install Python interpreter and base environment.
340
341
Core function that sets up the Python interpreter and standard library
342
in the virtual environment. Handles copying/linking Python executable,
343
standard library modules, and required system files.
344
345
Parameters:
346
- home_dir (str): Virtual environment home directory
347
- lib_dir (str): Library directory path
348
- inc_dir (str): Include directory path
349
- bin_dir (str): Binary/executable directory path
350
- site_packages (bool): Whether to include system site-packages
351
- clear (bool): Whether to clear existing installation
352
- symlink (bool): Use symlinks when possible
353
354
Returns:
355
str: Path to installed Python executable
356
357
Raises:
358
OSError: If Python installation fails
359
"""
360
```
361
362
**Usage Examples:**
363
364
```python
365
import virtualenv
366
367
# Install distutils after environment creation
368
virtualenv.install_distutils('/path/to/env')
369
370
# Install activation scripts
371
virtualenv.install_activate('/path/to/env', '/path/to/env/bin', prompt='myproject')
372
373
# Install python-config script
374
virtualenv.install_python_config('/path/to/env', '/path/to/env/bin')
375
376
# Install Python interpreter and base environment
377
home, lib, inc, bin = virtualenv.path_locations('/path/to/env')
378
python_exe = virtualenv.install_python(home, lib, inc, bin, site_packages=False, clear=False)
379
print(f"Python installed at: {python_exe}")
380
```
381
382
### Platform-Specific Python Discovery
383
384
Discovers available Python installations on the system, particularly useful on Windows for finding registry-installed Python versions.
385
386
```python { .api }
387
def get_installed_pythons():
388
"""
389
Get mapping of available Python installations.
390
391
Returns a dictionary mapping Python version strings to executable paths.
392
On Windows, searches the registry for installed Python versions.
393
On Unix systems, returns empty dict (relies on PATH search).
394
395
Parameters:
396
None
397
398
Returns:
399
dict: Mapping of version strings to executable paths
400
Example: {'3.8': '/usr/bin/python3.8', '3.9': '/usr/bin/python3.9'}
401
"""
402
```
403
404
**Usage Examples:**
405
406
```python
407
import virtualenv
408
409
# Get all available Python installations
410
pythons = virtualenv.get_installed_pythons()
411
print(f"Available Python versions: {list(pythons.keys())}")
412
413
# Use specific version if available
414
if '3.8' in pythons:
415
virtualenv.create_environment('/path/to/myenv', python=pythons['3.8'])
416
```