A tool for creating isolated 'virtual' python environments
—
Helper functions for path resolution, file system operations, and environment introspection that support the core virtualenv functionality.
Functions for calculating standard virtual environment paths and performing path-related operations.
def path_locations(home_dir, dry_run=False):
"""
Calculate standard path locations for a virtual environment.
Determines the conventional directory structure for a virtual environment
including locations for the Python executable, libraries, includes, and
site-packages based on the target platform and Python version.
Parameters:
- home_dir (str): Virtual environment root directory
- dry_run (bool): If True, don't create any directories
Returns:
tuple: (home_dir, lib_dir, inc_dir, bin_dir) where:
- home_dir (str): Normalized home directory path
- lib_dir (str): Library directory path (site-packages parent)
- inc_dir (str): Include directory path for headers
- bin_dir (str): Binary/executable directory path
Example return values:
Unix: ('/path/to/env', '/path/to/env/lib/python3.8', '/path/to/env/include', '/path/to/env/bin')
Windows: ('C:\\path\\to\\env', 'C:\\path\\to\\env\\Lib', 'C:\\path\\to\\env\\Include', 'C:\\path\\to\\env\\Scripts')
"""Usage Examples:
import virtualenv
# Get standard paths for environment
home, lib, inc, bin = virtualenv.path_locations('/path/to/myenv')
print(f"Executables: {bin}")
print(f"Libraries: {lib}")
print(f"Headers: {inc}")
# Dry run without creating directories
home, lib, inc, bin = virtualenv.path_locations('/path/to/myenv', dry_run=True)Functions for detecting and validating executable files across different platforms.
def is_executable_file(fpath):
"""
Check if a file path is an executable file.
Verifies that the path exists, is a file (not directory), and has
executable permissions. Cross-platform compatible function that
handles Windows executable extensions and Unix permissions.
Parameters:
- fpath (str): File path to check
Returns:
bool: True if file exists and is executable, False otherwise
"""
def is_executable(exe):
"""
Check if a path is executable.
Platform-aware check for executable permissions. On Unix systems
checks file permissions, on Windows checks file extension or
attempts execution test.
Parameters:
- exe (str): Path to check for executable permissions
Returns:
bool: True if path has executable permissions
"""Usage Examples:
import virtualenv
# Check if Python executable exists and is executable
python_path = '/usr/bin/python3'
if virtualenv.is_executable_file(python_path):
print(f"{python_path} is a valid executable")
# Check executable permissions only
if virtualenv.is_executable('/path/to/script'):
print("Script has executable permissions")Utility functions for finding files and manipulating paths within the virtualenv context.
def find_module_filename(modname):
"""
Find the filename for a Python module.
Locates the file path for a given Python module name, useful for
finding system modules that need to be copied to virtual environments.
Parameters:
- modname (str): Python module name (e.g., 'os', 'sys', 'encodings')
Returns:
str: Path to module file, or None if not found
Raises:
ImportError: If module cannot be imported or located
"""
def subst_path(prefix_path, prefix, home_dir):
"""
Substitute path prefix for relocating files.
Replaces path prefixes for making virtual environments relocatable
or adjusting paths during environment setup.
Parameters:
- prefix_path (str): Original path with old prefix
- prefix (str): Old prefix to replace
- home_dir (str): New prefix to substitute
Returns:
str: Path with substituted prefix
"""Usage Examples:
import virtualenv
# Find standard library module location
os_module_path = virtualenv.find_module_filename('os')
print(f"OS module located at: {os_module_path}")
# Substitute path prefix for relocation
old_path = '/old/prefix/lib/python3.8/site-packages'
new_path = virtualenv.subst_path(old_path, '/old/prefix', '/new/prefix')
print(f"Relocated path: {new_path}")Functions for locating virtualenv support files and resources.
def virtualenv_support_dirs():
"""
Get directories containing virtualenv support files.
Returns list of directories that contain wheel files, activation
scripts, and other resources needed for virtual environment creation.
Searches in package installation directory and user data directories.
Parameters:
None
Returns:
list: List of directory paths containing support files
"""Usage Examples:
import virtualenv
# Get support directories for finding wheels and resources
support_dirs = virtualenv.virtualenv_support_dirs()
print(f"Support directories: {support_dirs}")
# Use support directories in environment creation
virtualenv.create_environment('/path/to/env', search_dirs=support_dirs)Advanced path manipulation functions for environment setup and configuration.
def change_prefix(filename, dst_prefix):
"""
Change path prefixes in configuration files.
Modifies files that contain hardcoded paths (like .pth files or
configuration files) to use new path prefixes, essential for
making environments relocatable or adjusting paths during setup.
Parameters:
- filename (str): Path to file to modify
- dst_prefix (str): New prefix to use in file
Returns:
None (modifies file in place)
Raises:
OSError: If file cannot be read or written
"""
def make_relative_path(source, dest, dest_is_directory=True):
"""
Create relative path from source to destination.
Calculates the relative path needed to reach destination from source,
useful for creating relocatable symbolic links and references.
Parameters:
- source (str): Starting path
- dest (str): Target path
- dest_is_directory (bool): Whether destination is a directory
Returns:
str: Relative path from source to destination
"""Usage Examples:
import virtualenv
# Update configuration file with new prefix
virtualenv.change_prefix('/path/to/env/pyvenv.cfg', '/new/prefix')
# Create relative path for symlinks
rel_path = virtualenv.make_relative_path('/path/to/env/bin', '/path/to/env/lib')
print(f"Relative path: {rel_path}")Functions for executing system commands and managing subprocesses during environment creation.
def call_subprocess(
cmd,
show_stdout=True,
filter_stdout=None,
cwd=None,
raise_on_return_code=True,
extra_env=None,
remove_from_env=None,
stdin=None
):
"""
Execute subprocess with comprehensive option support.
Enhanced subprocess execution with output filtering, environment
manipulation, and error handling. Used internally for package
installation and system command execution.
Parameters:
- cmd (list): Command and arguments to execute
- show_stdout (bool): Whether to display stdout output
- filter_stdout (callable): Function to filter stdout lines
- cwd (str): Working directory for command execution
- raise_on_return_code (bool): Raise exception on non-zero exit codes
- extra_env (dict): Additional environment variables
- remove_from_env (list): Environment variables to remove
- stdin (str/bytes): Input to pass to command stdin
Returns:
None
Raises:
subprocess.CalledProcessError: If command fails and raise_on_return_code=True
"""
def filter_install_output(line):
"""
Filter installation output lines for display.
Determines whether installation output lines should be shown to user,
filtering out verbose or redundant information while preserving
important status messages and errors.
Parameters:
- line (str): Output line from installation process
Returns:
bool: True if line should be displayed, False to filter out
"""Usage Examples:
import virtualenv
# Execute command with custom environment
virtualenv.call_subprocess(
['pip', 'install', 'requests'],
cwd='/path/to/env',
extra_env={'PIP_INDEX_URL': 'https://custom.pypi.org/simple/'}
)
# Execute with output filtering
def my_filter(line):
return 'ERROR' in line or 'WARNING' in line
virtualenv.call_subprocess(
['pip', 'list'],
filter_stdout=my_filter
)
# Check if output line should be displayed
should_show = virtualenv.filter_install_output("Successfully installed package-1.0.0")Install with Tessl CLI
npx tessl i tessl/pypi-virtualenv