A tool for creating isolated 'virtual' python environments
—
Core functionality for creating and configuring virtual Python environments with extensive customization options including Python interpreter selection, package isolation controls, and dependency management.
Creates a complete virtual Python environment with all necessary components including Python interpreter, standard library, package management tools, and activation scripts.
def create_environment(
home_dir,
site_packages=False,
clear=False,
prompt=None,
search_dirs=None,
download=False,
no_setuptools=False,
no_pip=False,
no_wheel=False,
symlink=True
):
"""
Creates a new environment in home_dir.
If site_packages is true, then the global site-packages/ directory
will be on the path. If clear is true (default False) then the
environment will first be cleared.
Parameters:
- home_dir (str): Target directory for the virtual environment
- site_packages (bool): Include global site-packages in environment path
- clear (bool): Clear existing environment before creating new one
- prompt (str): Custom prompt prefix for the environment
- search_dirs (list): Directories to search for wheel packages
- download (bool): Download packages if not found locally
- no_setuptools (bool): Skip installing setuptools package
- no_pip (bool): Skip installing pip package manager
- no_wheel (bool): Skip installing wheel package
- symlink (bool): Use symlinks instead of copying files when possible
Returns:
None
Raises:
OSError: If directory creation fails
subprocess.CalledProcessError: If package installation fails
"""Usage Examples:
import virtualenv
# Create basic environment
virtualenv.create_environment('/path/to/myenv')
# Create environment with global packages accessible
virtualenv.create_environment('/path/to/myenv', site_packages=True)
# Create clean environment (removes existing first)
virtualenv.create_environment('/path/to/myenv', clear=True)
# Create environment without pip
virtualenv.create_environment('/path/to/myenv', no_pip=True)
# Create environment with custom prompt
virtualenv.create_environment('/path/to/myenv', prompt='myproject')Main entry point for command-line usage providing full option parsing and environment creation based on command-line arguments.
def main():
"""
Command-line interface entry point for virtualenv.
Parses command-line arguments using optparse and creates virtual
environment based on provided options. Handles all CLI flags including
verbose/quiet modes, Python interpreter selection, and environment
configuration options.
Command-line options include:
- --python PYTHON_EXE: Specify Python interpreter
- --clear: Clear existing environment
- --system-site-packages: Give access to global site-packages
- --always-copy: Always copy files rather than symlinking
- --prompt PROMPT: Custom environment prompt
- --no-setuptools: Don't install setuptools
- --no-pip: Don't install pip
- --no-wheel: Don't install wheel
- -v/--verbose: Increase verbosity
- -q/--quiet: Decrease verbosity
Parameters:
Uses sys.argv for argument parsing
Returns:
None (exits process with appropriate exit code)
Raises:
SystemExit: On argument parsing errors or environment creation failures
"""Usage Examples:
import virtualenv
import sys
# Use with custom arguments
sys.argv = ['virtualenv', '--python=python3.8', '/path/to/myenv']
virtualenv.main()
# Use with current sys.argv
virtualenv.main()Resolves and validates Python interpreter paths for environment creation, handling various Python installations and versions.
def resolve_interpreter(exe):
"""
Resolve Python interpreter path from executable name or path.
Takes a Python executable name (like 'python3.8') or path and resolves
it to an absolute path, validating that it's a working Python interpreter.
Handles platform-specific executable extensions and search paths.
Parameters:
- exe (str): Python executable name or path (e.g., 'python3.8', '/usr/bin/python')
Returns:
str: Absolute path to resolved Python interpreter
Raises:
RuntimeError: If interpreter cannot be found or is not executable
"""Usage Examples:
import virtualenv
# Resolve system Python
python_path = virtualenv.resolve_interpreter('python')
# Resolve specific version
python38_path = virtualenv.resolve_interpreter('python3.8')
# Resolve from absolute path
custom_path = virtualenv.resolve_interpreter('/opt/python/bin/python')Makes virtual environments relocatable by adjusting internal paths, useful for deployment and distribution scenarios.
def make_environment_relocatable(home_dir):
"""
Make a virtual environment relocatable.
Modifies the virtual environment to use relative paths instead of
absolute paths, allowing the environment directory to be moved to
different locations while maintaining functionality.
Parameters:
- home_dir (str): Path to virtual environment directory
Returns:
None
Raises:
OSError: If environment directory doesn't exist or modification fails
"""Usage Examples:
import virtualenv
# Create environment then make it relocatable
virtualenv.create_environment('/path/to/myenv')
virtualenv.make_environment_relocatable('/path/to/myenv')Functions for finding and installing wheel packages in virtual environments.
def find_wheels(projects, search_dirs):
"""
Find wheel files for given projects.
Searches specified directories for wheel files matching the given
project names. Returns mapping of project names to wheel file paths.
Parameters:
- projects (list): List of project names to find wheels for
- search_dirs (list): Directories to search for wheel files
Returns:
dict: Mapping of project names to wheel file paths
Example: {'pip': '/path/to/pip-20.0.0-py2.py3-none-any.whl'}
Raises:
OSError: If search directories cannot be accessed
"""Usage Examples:
import virtualenv
# Find wheels for specific projects
search_dirs = ['/path/to/wheels', '/another/wheel/dir']
wheels = virtualenv.find_wheels(['pip', 'setuptools'], search_dirs)
print(f"Found wheels: {wheels}")Installs wheel packages in virtual environments with support for local search directories and package downloading.
def install_wheel(project_names, py_executable, search_dirs=None, download=False):
"""
Install wheel packages in virtual environment.
Installs specified packages using wheel format, searching in provided
directories or downloading if needed. Commonly used for installing
setuptools, pip, and wheel in new environments.
Parameters:
- project_names (list): List of package names to install
- py_executable (str): Path to Python executable in target environment
- search_dirs (list, optional): Directories to search for wheel files
- download (bool): Download packages if not found locally
Returns:
None
Raises:
subprocess.CalledProcessError: If package installation fails
"""Usage Examples:
import virtualenv
# Install default packages
python_exe = '/path/to/myenv/bin/python'
virtualenv.install_wheel(['pip', 'setuptools', 'wheel'], python_exe)
# Install with custom search directories
search_dirs = ['/path/to/wheels']
virtualenv.install_wheel(['mypackage'], python_exe, search_dirs=search_dirs)
# Install with download fallback
virtualenv.install_wheel(['requests'], python_exe, download=True)Functions for installing specific components during virtual environment setup.
def install_distutils(home_dir):
"""
Install distutils configuration in virtual environment.
Sets up distutils configuration files and paths for proper
package installation behavior within the virtual environment.
Parameters:
- home_dir (str): Virtual environment home directory
Returns:
None
Raises:
OSError: If distutils configuration cannot be installed
"""
def install_activate(home_dir, bin_dir, prompt=None):
"""
Install activation scripts in virtual environment.
Creates platform-specific activation scripts (activate, activate.bat,
activate.ps1, etc.) that set up environment variables for using
the virtual environment.
Parameters:
- home_dir (str): Virtual environment home directory
- bin_dir (str): Binary/scripts directory
- prompt (str, optional): Custom prompt for activated environment
Returns:
None
Raises:
OSError: If activation scripts cannot be created
"""
def install_python_config(home_dir, bin_dir, prompt=None):
"""
Install Python configuration script in virtual environment.
Creates python-config script for querying Python configuration
information within the virtual environment context.
Parameters:
- home_dir (str): Virtual environment home directory
- bin_dir (str): Binary/scripts directory
- prompt (str, optional): Environment prompt
Returns:
None
Raises:
OSError: If python-config script cannot be created
"""
def install_python(home_dir, lib_dir, inc_dir, bin_dir, site_packages, clear, symlink=True):
"""
Install Python interpreter and base environment.
Core function that sets up the Python interpreter and standard library
in the virtual environment. Handles copying/linking Python executable,
standard library modules, and required system files.
Parameters:
- home_dir (str): Virtual environment home directory
- lib_dir (str): Library directory path
- inc_dir (str): Include directory path
- bin_dir (str): Binary/executable directory path
- site_packages (bool): Whether to include system site-packages
- clear (bool): Whether to clear existing installation
- symlink (bool): Use symlinks when possible
Returns:
str: Path to installed Python executable
Raises:
OSError: If Python installation fails
"""Usage Examples:
import virtualenv
# Install distutils after environment creation
virtualenv.install_distutils('/path/to/env')
# Install activation scripts
virtualenv.install_activate('/path/to/env', '/path/to/env/bin', prompt='myproject')
# Install python-config script
virtualenv.install_python_config('/path/to/env', '/path/to/env/bin')
# Install Python interpreter and base environment
home, lib, inc, bin = virtualenv.path_locations('/path/to/env')
python_exe = virtualenv.install_python(home, lib, inc, bin, site_packages=False, clear=False)
print(f"Python installed at: {python_exe}")Discovers available Python installations on the system, particularly useful on Windows for finding registry-installed Python versions.
def get_installed_pythons():
"""
Get mapping of available Python installations.
Returns a dictionary mapping Python version strings to executable paths.
On Windows, searches the registry for installed Python versions.
On Unix systems, returns empty dict (relies on PATH search).
Parameters:
None
Returns:
dict: Mapping of version strings to executable paths
Example: {'3.8': '/usr/bin/python3.8', '3.9': '/usr/bin/python3.9'}
"""Usage Examples:
import virtualenv
# Get all available Python installations
pythons = virtualenv.get_installed_pythons()
print(f"Available Python versions: {list(pythons.keys())}")
# Use specific version if available
if '3.8' in pythons:
virtualenv.create_environment('/path/to/myenv', python=pythons['3.8'])Install with Tessl CLI
npx tessl i tessl/pypi-virtualenv