0
# Utility Functions
1
2
Helper functions for path resolution, file system operations, and environment introspection that support the core virtualenv functionality.
3
4
## Capabilities
5
6
### Path and Directory Utilities
7
8
Functions for calculating standard virtual environment paths and performing path-related operations.
9
10
```python { .api }
11
def path_locations(home_dir, dry_run=False):
12
"""
13
Calculate standard path locations for a virtual environment.
14
15
Determines the conventional directory structure for a virtual environment
16
including locations for the Python executable, libraries, includes, and
17
site-packages based on the target platform and Python version.
18
19
Parameters:
20
- home_dir (str): Virtual environment root directory
21
- dry_run (bool): If True, don't create any directories
22
23
Returns:
24
tuple: (home_dir, lib_dir, inc_dir, bin_dir) where:
25
- home_dir (str): Normalized home directory path
26
- lib_dir (str): Library directory path (site-packages parent)
27
- inc_dir (str): Include directory path for headers
28
- bin_dir (str): Binary/executable directory path
29
30
Example return values:
31
Unix: ('/path/to/env', '/path/to/env/lib/python3.8', '/path/to/env/include', '/path/to/env/bin')
32
Windows: ('C:\\path\\to\\env', 'C:\\path\\to\\env\\Lib', 'C:\\path\\to\\env\\Include', 'C:\\path\\to\\env\\Scripts')
33
"""
34
```
35
36
**Usage Examples:**
37
38
```python
39
import virtualenv
40
41
# Get standard paths for environment
42
home, lib, inc, bin = virtualenv.path_locations('/path/to/myenv')
43
print(f"Executables: {bin}")
44
print(f"Libraries: {lib}")
45
print(f"Headers: {inc}")
46
47
# Dry run without creating directories
48
home, lib, inc, bin = virtualenv.path_locations('/path/to/myenv', dry_run=True)
49
```
50
51
### Executable Detection
52
53
Functions for detecting and validating executable files across different platforms.
54
55
```python { .api }
56
def is_executable_file(fpath):
57
"""
58
Check if a file path is an executable file.
59
60
Verifies that the path exists, is a file (not directory), and has
61
executable permissions. Cross-platform compatible function that
62
handles Windows executable extensions and Unix permissions.
63
64
Parameters:
65
- fpath (str): File path to check
66
67
Returns:
68
bool: True if file exists and is executable, False otherwise
69
"""
70
71
def is_executable(exe):
72
"""
73
Check if a path is executable.
74
75
Platform-aware check for executable permissions. On Unix systems
76
checks file permissions, on Windows checks file extension or
77
attempts execution test.
78
79
Parameters:
80
- exe (str): Path to check for executable permissions
81
82
Returns:
83
bool: True if path has executable permissions
84
"""
85
```
86
87
**Usage Examples:**
88
89
```python
90
import virtualenv
91
92
# Check if Python executable exists and is executable
93
python_path = '/usr/bin/python3'
94
if virtualenv.is_executable_file(python_path):
95
print(f"{python_path} is a valid executable")
96
97
# Check executable permissions only
98
if virtualenv.is_executable('/path/to/script'):
99
print("Script has executable permissions")
100
```
101
102
### File and Path Operations
103
104
Utility functions for finding files and manipulating paths within the virtualenv context.
105
106
```python { .api }
107
def find_module_filename(modname):
108
"""
109
Find the filename for a Python module.
110
111
Locates the file path for a given Python module name, useful for
112
finding system modules that need to be copied to virtual environments.
113
114
Parameters:
115
- modname (str): Python module name (e.g., 'os', 'sys', 'encodings')
116
117
Returns:
118
str: Path to module file, or None if not found
119
120
Raises:
121
ImportError: If module cannot be imported or located
122
"""
123
124
def subst_path(prefix_path, prefix, home_dir):
125
"""
126
Substitute path prefix for relocating files.
127
128
Replaces path prefixes for making virtual environments relocatable
129
or adjusting paths during environment setup.
130
131
Parameters:
132
- prefix_path (str): Original path with old prefix
133
- prefix (str): Old prefix to replace
134
- home_dir (str): New prefix to substitute
135
136
Returns:
137
str: Path with substituted prefix
138
"""
139
```
140
141
**Usage Examples:**
142
143
```python
144
import virtualenv
145
146
# Find standard library module location
147
os_module_path = virtualenv.find_module_filename('os')
148
print(f"OS module located at: {os_module_path}")
149
150
# Substitute path prefix for relocation
151
old_path = '/old/prefix/lib/python3.8/site-packages'
152
new_path = virtualenv.subst_path(old_path, '/old/prefix', '/new/prefix')
153
print(f"Relocated path: {new_path}")
154
```
155
156
### Support Directory Discovery
157
158
Functions for locating virtualenv support files and resources.
159
160
```python { .api }
161
def virtualenv_support_dirs():
162
"""
163
Get directories containing virtualenv support files.
164
165
Returns list of directories that contain wheel files, activation
166
scripts, and other resources needed for virtual environment creation.
167
Searches in package installation directory and user data directories.
168
169
Parameters:
170
None
171
172
Returns:
173
list: List of directory paths containing support files
174
"""
175
```
176
177
**Usage Examples:**
178
179
```python
180
import virtualenv
181
182
# Get support directories for finding wheels and resources
183
support_dirs = virtualenv.virtualenv_support_dirs()
184
print(f"Support directories: {support_dirs}")
185
186
# Use support directories in environment creation
187
virtualenv.create_environment('/path/to/env', search_dirs=support_dirs)
188
```
189
190
### Path Manipulation Utilities
191
192
Advanced path manipulation functions for environment setup and configuration.
193
194
```python { .api }
195
def change_prefix(filename, dst_prefix):
196
"""
197
Change path prefixes in configuration files.
198
199
Modifies files that contain hardcoded paths (like .pth files or
200
configuration files) to use new path prefixes, essential for
201
making environments relocatable or adjusting paths during setup.
202
203
Parameters:
204
- filename (str): Path to file to modify
205
- dst_prefix (str): New prefix to use in file
206
207
Returns:
208
None (modifies file in place)
209
210
Raises:
211
OSError: If file cannot be read or written
212
"""
213
214
def make_relative_path(source, dest, dest_is_directory=True):
215
"""
216
Create relative path from source to destination.
217
218
Calculates the relative path needed to reach destination from source,
219
useful for creating relocatable symbolic links and references.
220
221
Parameters:
222
- source (str): Starting path
223
- dest (str): Target path
224
- dest_is_directory (bool): Whether destination is a directory
225
226
Returns:
227
str: Relative path from source to destination
228
"""
229
```
230
231
**Usage Examples:**
232
233
```python
234
import virtualenv
235
236
# Update configuration file with new prefix
237
virtualenv.change_prefix('/path/to/env/pyvenv.cfg', '/new/prefix')
238
239
# Create relative path for symlinks
240
rel_path = virtualenv.make_relative_path('/path/to/env/bin', '/path/to/env/lib')
241
print(f"Relative path: {rel_path}")
242
```
243
244
### Process and Subprocess Utilities
245
246
Functions for executing system commands and managing subprocesses during environment creation.
247
248
```python { .api }
249
def call_subprocess(
250
cmd,
251
show_stdout=True,
252
filter_stdout=None,
253
cwd=None,
254
raise_on_return_code=True,
255
extra_env=None,
256
remove_from_env=None,
257
stdin=None
258
):
259
"""
260
Execute subprocess with comprehensive option support.
261
262
Enhanced subprocess execution with output filtering, environment
263
manipulation, and error handling. Used internally for package
264
installation and system command execution.
265
266
Parameters:
267
- cmd (list): Command and arguments to execute
268
- show_stdout (bool): Whether to display stdout output
269
- filter_stdout (callable): Function to filter stdout lines
270
- cwd (str): Working directory for command execution
271
- raise_on_return_code (bool): Raise exception on non-zero exit codes
272
- extra_env (dict): Additional environment variables
273
- remove_from_env (list): Environment variables to remove
274
- stdin (str/bytes): Input to pass to command stdin
275
276
Returns:
277
None
278
279
Raises:
280
subprocess.CalledProcessError: If command fails and raise_on_return_code=True
281
"""
282
283
def filter_install_output(line):
284
"""
285
Filter installation output lines for display.
286
287
Determines whether installation output lines should be shown to user,
288
filtering out verbose or redundant information while preserving
289
important status messages and errors.
290
291
Parameters:
292
- line (str): Output line from installation process
293
294
Returns:
295
bool: True if line should be displayed, False to filter out
296
"""
297
```
298
299
**Usage Examples:**
300
301
```python
302
import virtualenv
303
304
# Execute command with custom environment
305
virtualenv.call_subprocess(
306
['pip', 'install', 'requests'],
307
cwd='/path/to/env',
308
extra_env={'PIP_INDEX_URL': 'https://custom.pypi.org/simple/'}
309
)
310
311
# Execute with output filtering
312
def my_filter(line):
313
return 'ERROR' in line or 'WARNING' in line
314
315
virtualenv.call_subprocess(
316
['pip', 'list'],
317
filter_stdout=my_filter
318
)
319
320
# Check if output line should be displayed
321
should_show = virtualenv.filter_install_output("Successfully installed package-1.0.0")
322
```