### Install with version specifiers Source: https://parisneo.github.io/pipmaster/_sources/user_guide/installing.rst.txt Shows how to install packages with version specifiers using pm.install and pm.install_multiple. Includes examples for >=, <, ==, and ~= specifiers. ```python pm.install("requests>=2.25.0") pm.install("django<4.0") pm.install_multiple(["pandas==1.5.3", "numpy~=1.23.0"]) # Compatible release ``` -------------------------------- ### Install with custom index URL Source: https://parisneo.github.io/pipmaster/user_guide/installing.html Shows how to pass an index_url to install, install_multiple, and install_requirements. The example uses a PyTorch index URL for CUDA 12.1. ```python pytorch_index = "https://download.pytorch.org/whl/cu121" # Example pm.install("torch", index_url=pytorch_index) pm.install_multiple(["torchvision", "torchaudio"], index_url=pytorch_index) pm.install_requirements("torch_reqs.txt", index_url=pytorch_index) ``` -------------------------------- ### Install in editable mode Source: https://parisneo.github.io/pipmaster/_sources/user_guide/installing.rst.txt Demonstrates using pm.install_edit to install a local package in editable mode. The example is commented out. ```python # Assuming you have a package source in a directory named 'my_local_project' # pm.install_edit("./my_local_project") # Uncomment to run ``` -------------------------------- ### Install based on version requirements Source: https://parisneo.github.io/pipmaster/_sources/user_guide/installing.rst.txt Demonstrates pm.install_if_missing to install a package only if missing or if the installed version doesn't meet the specified requirement. Includes examples for version specifiers and always_update. ```python # Ensure numpy is at least version 1.21.0 pm.install_if_missing("numpy", version_specifier=">=1.21.0") # Ensure requests is exactly version 2.28.1 pm.install_if_missing("requests", version_specifier="==2.28.1") # Ensure requests is installed, and update to latest if already present pm.install_if_missing("requests", always_update=True) ``` -------------------------------- ### Install and uninstall packages with uv manager Source: https://parisneo.github.io/pipmaster/_sources/user_guide/uv.rst.txt Install multiple packages with install_multiple and uninstall a package with uninstall, both with verbose output. This example assumes an environment has already been created and targeted. ```python # ... (previous code for creating the environment) ... try: uv_manager = get_uv_manager() if uv_manager.create_env(path=env_path): print("Environment created. Now installing packages...") # Install multiple packages uv_manager.install_multiple(["numpy", "pandas"], verbose=True) # You can now use this environment to run code # (e.g., using subprocess with uv_manager.python_executable) print("\nUninstalling pandas...") uv_manager.uninstall("pandas", verbose=True) # ... (error handling and cleanup) ... ``` -------------------------------- ### Example Async Usage with async_install and run_in_executor Source: https://parisneo.github.io/pipmaster/_sources/user_guide/core_concepts.rst.txt Demonstrates asynchronous usage of pipmaster. It installs 'httpx' using async_install, then runs the synchronous is_installed check in an asyncio executor to avoid blocking. The example includes a commented-out asyncio.run call to execute the async function. ```python import pipmaster as pm import asyncio async def manage_packages_async(): print("Async: Installing httpx...") await pm.async_install("httpx") print("Async: Checking requests (sync check in executor)...") loop = asyncio.get_running_loop() # Run the synchronous is_installed function in the default executor req_installed = await loop.run_in_executor(None, pm.is_installed, "requests") print(f"Async: Is requests installed? {req_installed}") # To run this: # asyncio.run(manage_packages_async()) ``` -------------------------------- ### Install with custom index URL Source: https://parisneo.github.io/pipmaster/_sources/user_guide/installing.rst.txt Shows how to pass a custom index_url to various installation functions, including install, install_multiple, and install_requirements. ```python pytorch_index = "https://download.pytorch.org/whl/cu121" # Example pm.install("torch", index_url=pytorch_index) pm.install_multiple(["torchvision", "torchaudio"], index_url=pytorch_index) pm.install_requirements("torch_reqs.txt", index_url=pytorch_index) ``` -------------------------------- ### Install and uninstall packages with uv Source: https://parisneo.github.io/pipmaster/user_guide/uv.html Install multiple packages and uninstall one using the uv manager. The example shows creating an environment, installing numpy and pandas, then uninstalling pandas. ```python # ... (previous code for creating the environment) ... try: uv_manager = get_uv_manager() if uv_manager.create_env(path=env_path): print("Environment created. Now installing packages...") # Install multiple packages uv_manager.install_multiple(["numpy", "pandas"], verbose=True) # You can now use this environment to run code # (e.g., using subprocess with uv_manager.python_executable) print("\nUninstalling pandas...") uv_manager.uninstall("pandas", verbose=True) # ... (error handling and cleanup) ... ``` -------------------------------- ### Install from requirements file Source: https://parisneo.github.io/pipmaster/_sources/user_guide/installing.rst.txt Shows how to create a requirements.txt file and then install all packages listed in it using pm.install_requirements. ```python # Create the file first for the example with open("requirements.txt", "w") as f: f.write("click>=8.0\nflask\nrich ; python_version >= '3.6'\n") pm.install_requirements("requirements.txt") ``` -------------------------------- ### AsyncPackageManager.install() Source: https://parisneo.github.io/pipmaster/api/async.html Asynchronously installs a single package with visual feedback. ```APIDOC ## [ASYNC] AsyncPackageManager.install() ### Description Asynchronously installs a single package with visual feedback. ### Method Async method ### Endpoint AsyncPackageManager.install() ### Parameters #### Method Parameters - **package** (str) - Required - The name of the package to install. - **index_url** (str | None) - Optional - The index URL to use for installation. - **force_reinstall** (bool) - Optional - Whether to force reinstallation. - **upgrade** (bool) - Optional - Whether to upgrade the package. - **extra_args** (List[str] | None) - Optional - Additional arguments to pass to pip. - **dry_run** (bool) - Optional - If True, only simulate the installation. - **verbose** (bool) - Optional - If True, enable verbose output. ### Returns - **bool** - True if the installation succeeds, False otherwise. ### Response Example ```json { "success": true } ``` ``` -------------------------------- ### Async install method Source: https://parisneo.github.io/pipmaster/_modules/pipmaster/async_package_manager.html Asynchronously installs a package with optional upgrade, force-reinstall, index URL, and extra args. Provides visual feedback via a spinner or logs based on verbose/dry_run flags. Returns True on success, False on failure. ```python async def install( self, package: str, index_url: Optional[str] = None, force_reinstall: bool = False, upgrade: bool = True, extra_args: Optional[List[str]] = None, dry_run: bool = False, verbose: bool = False, ) -> bool: """Async install with visual feedback.""" command = ["install"] if upgrade: command.append("--upgrade") if force_reinstall: command.append("--force-reinstall") if index_url: command.extend(["--index-url", index_url]) if extra_args: command.extend(extra_args) command.append(package) action_emoji = EMOJI['update'] if upgrade else EMOJI['install'] action_text = "Updating" if upgrade else "Installing" msg = f"{action_emoji} [Async] {action_text}: {package}" if verbose or dry_run: logger.info(msg) success, _ = await self._run_command(command, dry_run=dry_run, verbose=verbose, capture_output=False) if success: logger.info(f"{EMOJI['sparkles']} [Async] Successfully handled: {package}") else: logger.error(f"{EMOJI['cross']} [Async] Failed to handle: {package}") else: with ASCIIColors.status(msg, spinner="dots", spinner_style="bold cyan") as status: success, _ = await self._run_command(command, dry_run=dry_run, verbose=verbose, capture_output=False) if success: logger.debug(f"{EMOJI['sparkles']} [Async] Successfully handled: {package}") else: logger.error(f"{EMOJI['cross']} [Async] Failed to handle: {package}") return success ``` -------------------------------- ### Get installed version with pm.get_installed_version Source: https://parisneo.github.io/pipmaster/_sources/user_guide/checking.rst.txt Retrieve the version string of an installed package using pm.get_installed_version. Returns None if the package is not found. The example checks 'packaging' and prints the version or a not-found message. ```python package_name = "packaging" # Dependency of pipmaster version = pm.get_installed_version(package_name) if version: print(f"Installed version of '{package_name}': {version}") else: print(f"'{package_name}' not found.") ``` -------------------------------- ### Install a package with pm.install Source: https://parisneo.github.io/pipmaster/_sources/getting_started.rst.txt Use pm.install to ensure a package is installed, upgrading if already present by default. Prints success or failure messages. ```python package_name = "requests" print(f"Ensuring '{package_name}' is installed...") if pm.install(package_name): print(f"'{package_name}' installed or already up-to-date.") else: print(f"Failed to install '{package_name}'.") ``` -------------------------------- ### async_install(package: str, **kwargs: Any) -> bool Source: https://parisneo.github.io/pipmaster/_modules/pipmaster/async_package_manager.html Asynchronously installs a single package. ```APIDOC ## [ASYNC] async_install ### Description Asynchronously installs a single package. ### Method ASYNC ### Endpoint async_install ### Parameters - **package** (str) - Required - The name of the package to install. - **kwargs** (Any) - Optional - Additional keyword arguments passed to the underlying install method. ### Returns - **bool** - True if installation succeeded, False otherwise. ### Example ```python result = await async_install('requests') ``` ``` -------------------------------- ### Async installation with pm.async_install Source: https://parisneo.github.io/pipmaster/_sources/getting_started.rst.txt Asynchronously install a package using pm.async_install inside an async function. The asyncio.run call is commented out. ```python async def install_async_package(): pkg = "aiohttp" print(f"Asynchronously installing '{pkg}'...") if await pm.async_install(pkg): print(f"Async install of '{pkg}' succeeded.") else: print(f"Async install of '{pkg}' failed.") # To run the async function: # asyncio.run(install_async_package()) ``` -------------------------------- ### Synchronous progress callback example Source: https://parisneo.github.io/pipmaster/_sources/user_guide/async.rst.txt Shows how to define a synchronous progress callback for pm.ensure_packages. The callback receives a dictionary with status, message, package(s), progress/total, and success keys. Use this to display progress in a console or UI when installing packages synchronously. ```python import pipmaster as pm def my_callback(data): print(f"[{data['status'].upper()}] {data['message']}") if 'progress' in data: print(f" Progress: {data['progress']}/{data['total']}") pm.ensure_packages(["requests", "numpy", "pandas"], progress_callback=my_callback, verbose=True) ``` -------------------------------- ### Install exact version with install_version Source: https://parisneo.github.io/pipmaster/_sources/user_guide/installing.rst.txt Demonstrates using pm.install_version to install a specific exact version of a package. ```python pm.install_version("colorama", "0.4.6") ``` -------------------------------- ### async_install_if_missing(package: str, **kwargs: Any) -> bool Source: https://parisneo.github.io/pipmaster/_modules/pipmaster/async_package_manager.html Asynchronously installs a package only if it is not already installed. ```APIDOC ## [ASYNC] async_install_if_missing ### Description Conditionally installs a single package asynchronously, only if it is not already present. ### Method ASYNC ### Endpoint async_install_if_missing ### Parameters - **package** (str) - Required - The name of the package to install if missing. - **kwargs** (Any) - Optional - Additional keyword arguments passed to the underlying install method. ### Returns - **bool** - True if the package is installed or already present, False otherwise. ### Example ```python result = await async_install_if_missing('requests') ``` ``` -------------------------------- ### Install multiple packages if missing Source: https://parisneo.github.io/pipmaster/_sources/getting_started.rst.txt Install multiple packages only if they are missing, using pm.install_multiple_if_not_installed. ```python extras = ["rich", "tqdm"] # Example utility packages print(f"Installing missing packages from: {extras}") if pm.install_multiple_if_not_installed(extras): print("Checked/installed extra utility packages.") else: print("Failed to install some utility packages.") ``` -------------------------------- ### Async install_if_missing method Source: https://parisneo.github.io/pipmaster/_modules/pipmaster/async_package_manager.html Asynchronously checks if a package needs installation and installs it if necessary. Supports version specifiers, always_update flag, and progress callbacks. Returns True if already satisfied or successfully installed, False otherwise. ```python async def install_if_missing( self, package: str, version_specifier: Optional[str] = None, always_update: bool = False, index_url: Optional[str] = None, extra_args: Optional[List[str]] = None, dry_run: bool = False, verbose: bool = False, ) -> bool: """Async conditional install with visual feedback.""" loop = asyncio.get_running_loop() # We must pass the verbose argument as a keyword argument because run_in_executor # only takes *args. We use functools.partial or lambda, but here we can just # construct the call carefully. # Since _check_if_install_is_needed signature is (package, version_specifier, always_update, verbose) # We can pass them positionally. is_needed, install_target, force = await loop.run_in_executor( None, self._sync_pm_instance._check_if_install_is_needed, package, version_specifier, always_update, verbose ) if not is_needed: logger.debug(f"{EMOJI['check']} [Async] '{package}' already satisfied. Skipping.") return True return await self.install( install_target, index_url=index_url, upgrade=True, force_reinstall=force, extra_args=extra_args, dry_run=dry_run, verbose=verbose, ) ``` -------------------------------- ### Get detailed package info with pm.get_package_info Source: https://parisneo.github.io/pipmaster/_sources/user_guide/checking.rst.txt Retrieve the output of 'pip show ' for a package using pm.get_package_info. The example gets info about pipmaster itself and prints it or a message if not found. ```python info = pm.get_package_info("pipmaster") # Get info about pipmaster itself if info: print("\n--- pipmaster info ---") print(info) print("----------------------\n") else: print("Could not get info for pipmaster (is it installed?).") ``` -------------------------------- ### AsyncPackageManager.install_multiple() Source: https://parisneo.github.io/pipmaster/api/async.html Asynchronously installs multiple packages with progress feedback. ```APIDOC ## [ASYNC] AsyncPackageManager.install_multiple() ### Description Asynchronously installs multiple packages with progress feedback. ### Method Async method ### Endpoint AsyncPackageManager.install_multiple() ### Parameters #### Method Parameters - **packages** (List[str]) - Required - The list of packages to install. - **index_url** (str | None) - Optional - The index URL to use for installation. - **force_reinstall** (bool) - Optional - Whether to force reinstallation. - **upgrade** (bool) - Optional - Whether to upgrade the packages. - **extra_args** (List[str] | None) - Optional - Additional arguments to pass to pip. - **dry_run** (bool) - Optional - If True, only simulate the installation. - **verbose** (bool) - Optional - If True, enable verbose output. ### Returns - **bool** - True if all installations succeed, False otherwise. ### Response Example ```json { "success": true } ``` ``` -------------------------------- ### AsyncPackageManager.install_if_missing() Source: https://parisneo.github.io/pipmaster/api/async.html Asynchronously installs a package only if it is not already installed. ```APIDOC ## [ASYNC] AsyncPackageManager.install_if_missing() ### Description Asynchronously installs a package only if it is not already installed, with visual feedback. ### Method Async method ### Endpoint AsyncPackageManager.install_if_missing() ### Parameters #### Method Parameters - **package** (str) - Required - The name of the package to install. - **version_specifier** (str | None) - Optional - A version specifier for the package. - **always_update** (bool) - Optional - If True, always update the package even if installed. - **index_url** (str | None) - Optional - The index URL to use for installation. - **extra_args** (List[str] | None) - Optional - Additional arguments to pass to pip. - **dry_run** (bool) - Optional - If True, only simulate the installation. - **verbose** (bool) - Optional - If True, enable verbose output. ### Returns - **bool** - True if the installation succeeds, False otherwise. ### Response Example ```json { "success": true } ``` ``` -------------------------------- ### Async install_multiple method Source: https://parisneo.github.io/pipmaster/_modules/pipmaster/async_package_manager.html Builds a pip install command with optional flags, runs it with or without a status spinner, and returns success. Handles empty package lists and logs batch results. ```python async def install_multiple( self, packages: List[str], index_url: Optional[str] = None, force_reinstall: bool = False, upgrade: bool = True, extra_args: Optional[List[str]] = None, dry_run: bool = False, verbose: bool = False, ) -> bool: """Async install batch with progress feedback.""" if not packages: return True msg = f"{EMOJI['rocket']} [Async] Installing batch of {len(packages)} package(s)..." command = ["install"] if upgrade: command.append("--upgrade") if force_reinstall: command.append("--force-reinstall") if index_url: command.extend(["--index-url", index_url]) if extra_args: command.extend(extra_args) command.extend(packages) if verbose or dry_run: logger.info(msg) success, _ = await self._run_command(command, dry_run=dry_run, verbose=verbose, capture_output=False) if success: logger.info(f"{EMOJI['sparkles']} [Async] Batch complete: {len(packages)} package(s)") else: logger.error(f"{EMOJI['cross']} [Async] Batch failed") else: with ASCIIColors.status(msg, spinner="star", spinner_style="bold green") as status: success, _ = await self._run_command(command, dry_run=dry_run, verbose=verbose, capture_output=False) if success: logger.debug(f"{EMOJI['sparkles']} [Async] Batch complete: {len(packages)} package(s)") else: logger.error(f"{EMOJI['cross']} [Async] Batch failed") return success ``` -------------------------------- ### Install multiple packages with pm.install_multiple Source: https://parisneo.github.io/pipmaster/_sources/user_guide/installing.rst.txt Install or upgrade multiple packages in a single pip command using pm.install_multiple. This is more efficient than installing them individually. ```python packages_to_install = ["matplotlib", "seaborn", "plotly"] pm.install_multiple(packages_to_install) ``` -------------------------------- ### Async batch install with progress callback Source: https://parisneo.github.io/pipmaster/_modules/pipmaster/async_package_manager.html Processes a list of packages, logs progress, invokes install_multiple, and reports completion or failure via a progress callback. Supports both async and sync callbacks. ```python pkg_list_str = "', '".join(packages_to_process) if verbose: logger.info(f"{EMOJI['package']} [Async] Processing {len(packages_to_process)} packages: '{pkg_list_str}'") else: logger.debug(f"{EMOJI['package']} [Async] Processing {len(packages_to_process)} packages.") if progress_callback: data = { "status": "processing", "message": f"Installing {len(packages_to_process)} package(s)", "packages": packages_to_process, "count": len(packages_to_process) } if asyncio.iscoroutinefunction(progress_callback): await progress_callback(data) else: progress_callback(data) result = await self.install_multiple( packages=packages_to_process, index_url=index_url, force_reinstall=False, upgrade=True, extra_args=extra_args, dry_run=dry_run, verbose=verbose, ) if progress_callback: data = { "status": "complete" if result else "failed", "message": "Installation complete" if result else "Installation failed", "packages": packages_to_process, "success": result } if asyncio.iscoroutinefunction(progress_callback): await progress_callback(data) else: progress_callback(data) return result ``` -------------------------------- ### Install uv on macOS/Linux Source: https://parisneo.github.io/pipmaster/_sources/user_guide/uv.rst.txt Install the uv executable on macOS/Linux using the official installer script. The uv executable must be available in the system's PATH to use the pipmaster uv backend. ```bash # Example installation for macOS/Linux curl -LsSf https://astral.sh/uv/install.sh | sh # See the official uv documentation for other installation methods. ``` -------------------------------- ### Install single package with pm.install Source: https://parisneo.github.io/pipmaster/_sources/user_guide/installing.rst.txt Install a single package with pm.install. By default it acts like pip install --upgrade. Use upgrade=False to avoid upgrading, and force_reinstall=True to reinstall even if the latest version is present. ```python import pipmaster as pm # Install the latest version of 'requests', or upgrade if already installed pm.install("requests") # Install 'numpy' but *don't* upgrade it if it's already installed pm.install("numpy", upgrade=False) # Force reinstall 'pandas', even if the latest version is present pm.install("pandas", force_reinstall=True) ``` -------------------------------- ### Install package asynchronously with portable Python 3.12 Source: https://parisneo.github.io/pipmaster/_sources/user_guide/async_versions.rst.txt Creates an AsyncPackageManager for portable Python 3.12, installs 'rich' asynchronously, and verifies installation using run_in_executor because is_installed is synchronous. Uses the get_async_pip_manager_for_version factory. ```python import pipmaster as pm import asyncio async def main(): # Create an AsyncPackageManager that uses a portable Python 3.12 async_pm = pm.get_async_pip_manager_for_version("3.12", "./my_portable_venv") # Install a package asynchronously in that environment await async_pm.install("rich", verbose=True) # Verify installation (run in executor because ``is_installed`` is sync) loop = asyncio.get_running_loop() installed = await loop.run_in_executor(None, async_pm.is_installed, "rich") print(f"'rich' installed? {installed}") asyncio.run(main()) ``` -------------------------------- ### Check if a package is installed with pm.is_installed Source: https://parisneo.github.io/pipmaster/_sources/user_guide/checking.rst.txt Use pm.is_installed to determine if a package exists in the target environment. The example checks for 'requests' and a non-existent package, printing appropriate messages. ```python import pipmaster as pm if pm.is_installed("requests"): print("requests is installed.") else: print("requests is NOT installed.") # Check a non-existent package if not pm.is_installed("no_such_package_exists_i_hope"): print("Confirmed: The non-existent package is not installed.") ``` -------------------------------- ### async_install_multiple(packages: List[str], **kwargs: Any) -> bool Source: https://parisneo.github.io/pipmaster/_modules/pipmaster/async_package_manager.html Asynchronously installs multiple packages. ```APIDOC ## [ASYNC] async_install_multiple ### Description Installs multiple packages asynchronously. ### Method ASYNC ### Endpoint async_install_multiple ### Parameters - **packages** (List[str]) - Required - List of package names to install. - **kwargs** (Any) - Optional - Additional keyword arguments passed to the underlying install method. ### Returns - **bool** - True if all installations succeeded, False otherwise. ### Example ```python result = await async_install_multiple(['requests', 'flask']) ``` ``` -------------------------------- ### Targeting a Different Python Environment with PackageManager and get_pip_manager Source: https://parisneo.github.io/pipmaster/_sources/user_guide/core_concepts.rst.txt Shows how to create a PackageManager instance targeting the current environment by default, and how to target a specific virtual environment by providing its Python executable path. The example prints the target executable and installs 'requests' into the venv, catching FileNotFoundError if the path is invalid. ```python import pipmaster as pm import sys # Default manager targets the current environment default_pm = pm.PackageManager() print(f"Default targets: {default_pm.target_python_executable}") # is equivalent to: current_pm = pm.PackageManager(python_executable=sys.executable) print(f"Current targets: {current_pm.target_python_executable}") # Target a specific venv (replace with a valid path on your system) # venv_python_path = "/path/to/myenv/bin/python" # Linux/macOS venv_python_path = "C:/path/to/myenv/Scripts/python.exe" # Windows try: # Get a manager instance specifically for this environment venv_pm = pm.get_pip_manager(python_executable=venv_python_path) print(f"Targeting venv: {venv_pm.target_python_executable}") # Operations using venv_pm will affect the other environment venv_pm.install("requests") # Installs requests into the venv except FileNotFoundError: print(f"Warning: Path not found for target environment: {venv_python_path}") ``` -------------------------------- ### Check package installation and version Source: https://parisneo.github.io/pipmaster/_sources/getting_started.rst.txt Check if a package is installed and retrieve its version using pm.is_installed and pm.get_installed_version. ```python package_to_check = "packaging" # A dependency of pipmaster if pm.is_installed(package_to_check): version = pm.get_installed_version(package_to_check) print(f"'{package_to_check}' is installed, version: {version}") else: print(f"'{package_to_check}' is not installed.") ``` -------------------------------- ### Check version compatibility with pm.is_version_compatible Source: https://parisneo.github.io/pipmaster/_sources/user_guide/checking.rst.txt Use pm.is_version_compatible to check if the installed version meets a PEP 440 specifier. The example assumes 'packaging' version 23.2 and tests multiple specifiers, including a non-existent package returning False. ```python # Assume 'packaging' version 23.2 is installed for these examples # Check if >= 21.0 (Should be True) if pm.is_version_compatible("packaging", ">=21.0"): print("packaging version is >= 21.0") # Check if == 23.2 (Should be True) if pm.is_version_compatible("packaging", "==23.2"): print("packaging version is exactly 23.2") # Check if < 23.0 (Should be False) if not pm.is_version_compatible("packaging", "<23.0"): print("packaging version is NOT < 23.0") # Check against a non-existent package (will be False) if not pm.is_version_compatible("nonexistent_pkg", ">=1.0"): print("Compatibility check returns False for non-existent packages.") ``` -------------------------------- ### Set up development environment (bash) Source: https://parisneo.github.io/pipmaster/_sources/contributing.rst.txt Creates a virtual environment, activates it, and installs pipmaster in editable mode with dev dependencies. Use this before making changes. The activation command differs on Windows (commented out). ```bash python -m venv venv source venv/bin/activate # Linux/macOS # venv\Scripts\activate # Windows pip install -e ".[dev]" # Install in editable mode with dev dependencies ``` -------------------------------- ### Conditional Git install with ensure_packages Source: https://parisneo.github.io/pipmaster/_sources/user_guide/installing.rst.txt Define a conditional Git installation rule for ensure_packages. The rule installs from a Git repository only if the installed version does not meet the condition. ```python # This rule means: "We need diffusers>=0.25.0. # If not met, install from the main branch on GitHub." conditional_req = { "name": "diffusers", "vcs": "git+https://github.com/huggingface/diffusers.git", "condition": ">=0.25.0" } # This will trigger the git install if an older version is present pm.ensure_packages([conditional_req], verbose=True) ``` -------------------------------- ### Installing Specific Versions with Version Specifiers Source: https://parisneo.github.io/pipmaster/user_guide/installing.html Specify versions directly in the package string (PEP 508 format) for pm.install() or pm.install_multiple(). Use pm.install_version() for an exact version. ```python # Using install with version specifiers pm.install("requests>=2.25.0") pm.install("django<4.0") pm.install_multiple(["pandas==1.5.3", "numpy~=1.23.0"]) # Compatible release # Using install_version for an exact version pm.install_version("colorama", "0.4.6") ``` -------------------------------- ### Async ensure_packages method Source: https://parisneo.github.io/pipmaster/_modules/pipmaster/async_package_manager.html Asynchronously ensures a list of packages are installed, using a thread executor to call the synchronous check. Supports progress callbacks (sync or async) and returns True if all requirements are satisfied or installed successfully. ```python async def ensure_packages( self, requirements: Union[str, Dict[str, Any], List[str]], index_url: Optional[str] = None, extra_args: Optional[List[str]] = None, dry_run: bool = False, verbose: bool = False, progress_callback: Optional[callable] = None, ) -> bool: """Async ensure with pleasant batch feedback.""" loop = asyncio.get_running_loop() # Define a wrapper to call async callback from sync context def sync_progress_wrapper(data): if progress_callback and asyncio.iscoroutinefunction(progress_callback): # Schedule the async callback on the event loop try: loop.call_soon_threadsafe(lambda: asyncio.create_task(progress_callback(data))) except Exception: pass elif progress_callback: progress_callback(data) packages_to_process = await loop.run_in_executor( None, self._sync_pm_instance._get_packages_to_process, requirements, False, verbose, sync_progress_wrapper ) if not packages_to_process: msg = f"{EMOJI['check']} [Async] All requirements satisfied." logger.debug(msg) if progress_callback: if asyncio.iscoroutinefunction(progress_callback): await progress_callback({"status": "complete", "message": msg, "packages": []}) else: progress_callback({"status": "complete", "message": msg, "packages": []}) return True ``` -------------------------------- ### Create a virtual environment with uv Source: https://parisneo.github.io/pipmaster/user_guide/uv.html Create a new virtual environment using the uv manager. The example removes an existing environment, creates a new one, and prints the targeted Python executable. ```python import os import shutil from pipmaster import get_uv_manager env_path = "./my_uv_env" if os.path.exists(env_path): shutil.rmtree(env_path) try: uv_manager = get_uv_manager() print(f"Creating uv environment at: {env_path}") if uv_manager.create_env(path=env_path): print("Environment created successfully.") # The manager now targets this new environment for subsequent calls print(f"Manager now targets Python: {uv_manager.python_executable}") else: print("Failed to create environment.") except FileNotFoundError: print("Skipping example: 'uv' executable not found in PATH.") finally: if os.path.exists(env_path): shutil.rmtree(env_path) ``` -------------------------------- ### is_installed(package_name, version_specifier=None) Source: https://parisneo.github.io/pipmaster/user_guide/checking.html Checks if a package is installed, optionally verifying a version specifier. ```APIDOC ## is_installed(package_name, version_specifier=None) ### Description Determines if a package is installed in the target environment. Optionally checks if the installed version satisfies a PEP 440 version specifier. ### Parameters - **package_name** (str) - Required - The name of the package to check. - **version_specifier** (str) - Optional - A PEP 440 version specifier (e.g., ">=2.25.0") to check compatibility. ### Returns - **bool** - True if the package is installed (and meets the version specifier if provided), False otherwise. ### Example ```python import pipmaster as pm if pm.is_installed("requests"): print("requests is installed.") else: print("requests is NOT installed.") # With version specifier if pm.is_installed("requests", version_specifier=">=2.25.0"): print("requests >= 2.25.0 is installed.") ``` ``` -------------------------------- ### Conditional install with version specifier Source: https://parisneo.github.io/pipmaster/_sources/getting_started.rst.txt Install a package only if it does not meet the specified version specifier, using pm.install_if_missing with version_specifier. ```python # Ensure 'requests' version 2.25.0 or higher, but less than 3.0.0 specifier = ">=2.25.0,<3.0.0" print(f"Ensuring 'requests' meets specifier: '{specifier}'") if pm.install_if_missing("requests", version_specifier=specifier): print("'requests' requirement met or installation/update succeeded.") else: print("Failed to meet 'requests' requirement.") ``` -------------------------------- ### Directly Instantiate PackageManager with python_executable Source: https://parisneo.github.io/pipmaster/_sources/user_guide/environments.rst.txt Shows how to directly instantiate the PackageManager class with a python_executable path. The example is commented out and includes a placeholder for the path. ```python from pipmaster import PackageManager # venv_python_path = "/path/to/your/other/venv/bin/python" # EDIT THIS # try: # venv_pm = PackageManager(python_executable=venv_python_path) # # ... perform operations using venv_pm ... # except FileNotFoundError: # # Handle error ``` -------------------------------- ### Using AsyncPackageManager for structured async code Source: https://parisneo.github.io/pipmaster/_sources/user_guide/async.rst.txt Demonstrates using the AsyncPackageManager class to install packages asynchronously into a target environment. Includes running synchronous checks via an executor and handling errors like FileNotFoundError. ```python from pipmaster.async_package_manager import AsyncPackageManager import asyncio import sys async def manage_env_async(python_path=None): if python_path is None: python_path = sys.executable print(f"Using default environment: {python_path}") else: print(f"Targeting environment: {python_path}") try: async_pm = AsyncPackageManager(python_executable=python_path) # Example: Async install into the target environment await async_pm.install("rich") # Installs rich into the targeted env # Note: Checks still need executor for now loop = asyncio.get_running_loop() from pipmaster import PackageManager # Need sync version for check sync_pm_for_check = PackageManager(python_executable=python_path) is_rich_installed = await loop.run_in_executor( None, sync_pm_for_check.is_installed, "rich" ) print(f"Is 'rich' installed in target env? {is_rich_installed}") except FileNotFoundError: print(f"Error: Python executable not found at {python_path}") except Exception as e: print(f"An error occurred: {e}") # Example usage: # venv_python_path = "/path/to/your/other/venv/bin/python" # EDIT THIS # asyncio.run(manage_env_async(venv_python_path)) # asyncio.run(manage_env_async()) # Target current env ``` -------------------------------- ### Uninstall multiple packages with pm.uninstall_multiple Source: https://parisneo.github.io/pipmaster/_sources/user_guide/uninstalling.rst.txt Installs 'colorama' and 'rich' first, then uninstalls them using pm.uninstall_multiple. Prints a list of packages to remove and success or failure messages. ```python # Install a couple of packages first print("\nInstalling 'colorama' and 'rich' for multiple uninstall example...") pm.install_multiple(["colorama", "rich"]) packages_to_remove = ["colorama", "rich"] print(f"\nUninstalling: {', '.join(packages_to_remove)}") if pm.uninstall_multiple(packages_to_remove): print("Packages uninstalled successfully.") else: print("Failed to uninstall one or more packages.") ``` -------------------------------- ### Async progress callback example Source: https://parisneo.github.io/pipmaster/_sources/api/async.rst.txt Shows an async callback function that receives progress updates with status, message, packages, and progress fields. Use it with async_ensure_packages to monitor package processing. ```python async def progress_handler(data): print(f"{data['status']}: {data['message']}") if data.get('packages'): print(f" Packages: {data['packages']}") await async_ensure_packages(["requests"], progress_callback=progress_handler) ``` -------------------------------- ### Run ephemeral tools with run_with_uvx Source: https://parisneo.github.io/pipmaster/_sources/user_guide/uv.rst.txt Run a tool in a temporary ephemeral environment using run_with_uvx, equivalent to uvx or uv tool run. No environment path is needed; the example runs black --version and shows a commented-out ruff check . call. ```python from pipmaster import get_uv_manager try: # No environment path is needed for this uv_manager = get_uv_manager() print("Running 'black --version' with uvx...") uv_manager.run_with_uvx(["black", "--version"], verbose=True) print("\nRunning 'ruff check .' with uvx...") # This would check the current directory with ruff # uv_manager.run_with_uvx(["ruff", "check", "."], verbose=True) except FileNotFoundError: print("Skipping example: 'uv' executable not found in PATH.") ``` -------------------------------- ### Uninstall a single package with pm.uninstall Source: https://parisneo.github.io/pipmaster/_sources/user_guide/uninstalling.rst.txt Installs 'termcolor' first, then uninstalls it using pm.uninstall. Checks pm.is_installed before uninstalling and prints success or failure messages. ```python import pipmaster as pm # First, let's install something to uninstall print("Installing 'termcolor' for uninstallation example...") pm.install("termcolor") if pm.is_installed("termcolor"): print("Uninstalling 'termcolor'...") if pm.uninstall("termcolor"): print("'termcolor' successfully uninstalled.") else: print("Failed to uninstall 'termcolor'.") else: print("'termcolor' was not installed.") ``` -------------------------------- ### Import pipmaster and asyncio Source: https://parisneo.github.io/pipmaster/_sources/getting_started.rst.txt Import the pipmaster library and asyncio for later async examples. ```python import pipmaster as pm import asyncio # Needed for async examples later ``` -------------------------------- ### Sync environment with ensure_requirements Source: https://parisneo.github.io/pipmaster/_sources/user_guide/installing.rst.txt Sync the environment with a requirements.txt file using ensure_requirements. The file can include index-url options and comments. The function installs only what's needed and returns True when the environment matches. ```text --extra-index-url https://download.pytorch.org/whl/cu121 torch # A comment rich ; python_version >= '3.8' ``` ```python import pipmaster as pm # Create the file for the example with open("requirements.txt", "w") as f: f.write("--extra-index-url https://download.pytorch.org/whl/cu121\n") f.write("torch\n") f.write("rich ; python_version >= '3.8'\n") # This single command ensures the environment matches the file. # It handles the index-url option and installs only what's needed. if pm.ensure_requirements("requirements.txt", verbose=True): print("Environment is now in sync with requirements.txt!") ``` -------------------------------- ### Async requirements.txt processing Source: https://parisneo.github.io/pipmaster/_modules/pipmaster/async_package_manager.html Reads a requirements file, filters comments and empty lines, separates pip options, and delegates to ensure_packages for installation. Returns False if the file is not found. ```python async def ensure_requirements( self, requirements_file: str, dry_run: bool = False, verbose: bool = False, ) -> bool: """Async requirements.txt processing.""" try: with open(requirements_file, 'r', encoding='utf-8') as f: lines = f.readlines() except FileNotFoundError: logger.error(f"{EMOJI['cross']} [Async] Requirements file not found: {requirements_file}") return False requirements_list = [] pip_options = [] for line in lines: line = line.strip() if not line or line.startswith('#'): continue if line.startswith('-'): pip_options.extend(shlex.split(line)) else: package_req = line.split('#')[0].strip() if package_req: requirements_list.append(package_req) if not requirements_list and not pip_options: logger.debug(f"{EMOJI['info']} [Async] No requirements in {requirements_file}") return True if verbose: logger.info(f"{EMOJI['package']} [Async] Processing {len(requirements_list)} requirements from {requirements_file}") return await self.ensure_packages( requirements=requirements_list, index_url=None, extra_args=pip_options, dry_run=dry_run, verbose=verbose ) ``` -------------------------------- ### Automatic Environment Creation with PackageManager venv_path Source: https://parisneo.github.io/pipmaster/_sources/user_guide/environments.rst.txt Demonstrates automatic virtual environment creation by passing a venv_path to PackageManager. If the environment does not exist, pipmaster creates it; the example cleans up the created environment afterward. ```python from pipmaster import PackageManager import os import shutil # Path for our new environment new_venv_path = "./my_new_test_venv" # Clean up from previous runs if it exists if os.path.exists(new_venv_path): shutil.rmtree(new_venv_path) print(f"Attempting to create and use a venv at: {new_venv_path}") # This will create the venv because it doesn't exist venv_pm = PackageManager(venv_path=new_venv_path) print(f"PackageManager is now targeting: {venv_pm.target_python_executable}") # Install a package into the newly created environment venv_pm.install("rich", verbose=True) # Clean up the created environment shutil.rmtree(new_venv_path) ``` -------------------------------- ### async_check_vulnerabilities(**kwargs: Any) -> Tuple[bool, str] Source: https://parisneo.github.io/pipmaster/_modules/pipmaster/async_package_manager.html Asynchronously checks for vulnerabilities in installed packages. ```APIDOC ## [ASYNC] async_check_vulnerabilities ### Description Checks for vulnerabilities asynchronously. ### Method ASYNC ### Endpoint async_check_vulnerabilities ### Parameters - **kwargs** (Any) - Optional - Additional keyword arguments passed to the underlying vulnerability check method. ### Returns - **Tuple[bool, str]** - A tuple containing a boolean indicating if vulnerabilities were found, and a string with details. ### Example ```python has_vulns, details = await async_check_vulnerabilities() ``` ``` -------------------------------- ### Pass extra arguments to pip uninstall Source: https://parisneo.github.io/pipmaster/_sources/user_guide/uninstalling.rst.txt Shows how to pass extra arguments to pip uninstall using the extra_args parameter. The example is commented out and demonstrates uninstalling a package from a requirements file. ```python # Example: Uninstall package installed from a requirements file # pm.uninstall("package-from-reqs", extra_args=["-r", "requirements.txt"]) # Note: This specific use case might be less common programmatically. ``` -------------------------------- ### Ensure requirements from file asynchronously Source: https://parisneo.github.io/pipmaster/_sources/user_guide/async_versions.rst.txt Shows how to use the async factory to ensure requirements from a requirements.txt file in a portable Python environment. The function is defined but not called in the example. ```python async def ensure_requirements(): async_pm = pm.get_async_pip_manager_for_version("3.12", "./venv3_12") await async_pm.ensure_requirements("requirements.txt", verbose=True) ``` -------------------------------- ### is_version_compatible(package_name, version_specifier) Source: https://parisneo.github.io/pipmaster/user_guide/checking.html Checks if the installed version of a package satisfies a PEP 440 version specifier. ```APIDOC ## is_version_compatible(package_name, version_specifier) ### Description Checks if the installed version of a package meets a specific version requirement defined by a PEP 440 specifier string. ### Parameters - **package_name** (str) - Required - The name of the package to check. - **version_specifier** (str) - Required - A PEP 440 version specifier (e.g., ">=21.0", "==23.2", "<23.0"). ### Returns - **bool** - True if the installed version satisfies the specifier, False otherwise (including if the package is not installed). ### Example ```python # Assume 'packaging' version 23.2 is installed if pm.is_version_compatible("packaging", ">=21.0"): print("packaging version is >= 21.0") if pm.is_version_compatible("packaging", "==23.2"): print("packaging version is exactly 23.2") if not pm.is_version_compatible("packaging", "<23.0"): print("packaging version is NOT < 23.0") ``` ``` -------------------------------- ### Create uv virtual environment with create_env Source: https://parisneo.github.io/pipmaster/_sources/user_guide/uv.rst.txt Create a new virtual environment with uv using create_env. The manager targets the new environment for subsequent calls, and the example cleans up the environment in a finally block. ```python import os import shutil from pipmaster import get_uv_manager env_path = "./my_uv_env" if os.path.exists(env_path): shutil.rmtree(env_path) try: uv_manager = get_uv_manager() print(f"Creating uv environment at: {env_path}") if uv_manager.create_env(path=env_path): print("Environment created successfully.") # The manager now targets this new environment for subsequent calls print(f"Manager now targets Python: {uv_manager.python_executable}") else: print("Failed to create environment.") except FileNotFoundError: print("Skipping example: 'uv' executable not found in PATH.") finally: if os.path.exists(env_path): shutil.rmtree(env_path) ``` -------------------------------- ### get_installed_version(package_name) Source: https://parisneo.github.io/pipmaster/user_guide/checking.html Gets the installed version of a package. ```APIDOC ## get_installed_version(package_name) ### Description Retrieves the version string of an installed package. Returns None if the package is not found. ### Parameters - **package_name** (str) - Required - The name of the package to query. ### Returns - **str or None** - The installed version string, or None if the package is not installed. ### Example ```python package_name = "packaging" version = pm.get_installed_version(package_name) if version: print(f"Installed version of '{package_name}': {version}") else: print(f"'{package_name}' not found.") ``` ```