### Install Command Configuration Example Source: https://github.com/python/pymanager/blob/main/_autodocs/configuration.md Customize package index sources, enable specific shortcut types, and control site-package preservation during upgrades for the 'install' command. This example sets an internal mirror as the primary source and enables console shortcuts. ```json { "install": { "source": "https://internal-mirror.corp/python/index.json", "fallback_source": "https://www.python.org/ftp/python/index-windows.json", "enable_shortcut_kinds": ["console"], "preserve_site_on_upgrade": false } } ``` -------------------------------- ### Install Dictionary Example Source: https://github.com/python/pymanager/blob/main/_autodocs/types.md Represents an installed Python runtime. Use this structure to define and manage Python installations. ```python install = { "id": "python-3.12.0-amd64", "display-name": "Python 3.12.0", "company": "PythonCore", "tag": "3.12", "sort-version": Version("3.12.0"), "prefix": Path("C:\\Python312"), "executable": Path("C:\\Python312\\python.exe"), "alias": [ {"name": "python.exe", "target": "python.exe"}, {"name": "python3.exe", "target": "python.exe"}, ], "run-for": [ {"tag": "3.12", "target": "python.exe"}, ], } ``` -------------------------------- ### Configuration Dictionary Example Source: https://github.com/python/pymanager/blob/main/_autodocs/types.md An example of a complete configuration dictionary, including top-level fields and nested 'install' settings. Useful for setting up Pymanager's behavior. ```python config = { "log_level": 20, # INFO "confirm": True, "automatic_install": True, "default_tag": "3.12", "install": { "source": "https://www.python.org/ftp/python/index-windows.json", "enable_shortcut_kinds": ["console"], } } ``` -------------------------------- ### Minimal Configuration Example Source: https://github.com/python/pymanager/blob/main/_autodocs/README.md A basic JSON configuration for enabling automatic Python installations. ```json { "automatic_install": true } ``` -------------------------------- ### List Command Configuration Example Source: https://github.com/python/pymanager/blob/main/_autodocs/configuration.md Configure the output format and whether to include unmanaged installations for the 'list' command. Use 'json' format for machine-readable output and set 'unmanaged' to false to exclude non-PyManager installs. ```json { "list": { "format": "json", "unmanaged": false } } ``` -------------------------------- ### get_install_shortcuts Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/aliasutils-pep514utils.md Generates shortcut definitions for the Windows Start menu for a given Python installation, including documentation shortcuts if available. Shortcuts are named with the version and platform. ```APIDOC ## get_install_shortcuts ### Description Create Windows Start menu shortcuts for an install. This function generates shortcut definitions for the Start menu, creates documentation shortcuts if available, and names shortcuts with the version and platform. ### Function Signature ```python def get_install_shortcuts(install: dict, cmd: BaseCommand) -> list[dict] ``` ### Parameters - **install** (dict) - Required - Install dictionary - **cmd** (BaseCommand) - Required - Command with configuration and paths ### Returns list[dict] - Shortcut information ``` -------------------------------- ### NoInstallFoundError Usage Example Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/exceptions.md Demonstrates raising and catching NoInstallFoundError, which is used when a requested Python runtime is not installed. The example shows how to access the 'tag' attribute to see what was searched for. ```python from manage.exceptions import NoInstallFoundError try: raise NoInstallFoundError(tag="3.12") except NoInstallFoundError as e: print(f"Missing runtime: {e}") print(f"Searched for: {e.tag}") ``` -------------------------------- ### Get Installs from __install__.json Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/installs.md Internal function to generate install dictionaries from __install__.json files. It resolves paths for individual install entries. ```python def _get_installs(install_dir: Path) -> Generator[dict, None, None] ``` -------------------------------- ### Enterprise Configuration Example Source: https://github.com/python/pymanager/blob/main/_autodocs/README.md An advanced JSON configuration for enterprise environments, specifying custom install sources and signature requirements. ```json { "install": { "source": "https://internal-mirror.corp/python", "enable_shortcut_kinds": ["console"] }, "source_settings": { "https://internal-mirror.corp/python": { "requires_signature": true, "required_root_subject": "CN=InternalCA" } } } ``` -------------------------------- ### Installing Python Runtimes Source: https://github.com/python/pymanager/blob/main/_autodocs/README.md Instantiate and execute the `InstallCommand` to download and install a specified Python runtime. ```python from manage.commands import InstallCommand cmd = InstallCommand(["install", "3.12"], root=Path(".")) cmd.execute() ``` -------------------------------- ### Install build and test tools Source: https://github.com/python/pymanager/blob/main/README.md Install pymsbuild and pytest for running the test suite locally. This setup allows for quick iteration on Python code without a full project rebuild. ```bash python -m pip install pymsbuild pytest ``` -------------------------------- ### Install Python Runtime Command Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/commands.md Executes the 'install' command to download and install Python runtimes. Supports options for refreshing shortcuts and specifying sources. ```python class InstallCommand(BaseCommand): CMD = "install" USAGE_LINE = "install " ... ``` ```python # Install Python 3.12 and update shortcuts cmd = InstallCommand(["install", "--refresh", "3.12"], root=Path("/opt/pymanager")) cmd.execute() ``` -------------------------------- ### Get Installed Python Runtimes Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/commands.md Retrieves a list of installed Python runtimes. Optionally includes unmanaged installs and marks the default install. ```python def get_installs(self, *, include_unmanaged: bool = False, set_default: bool = True) -> list[dict]: pass ``` -------------------------------- ### NoInstallsError Usage Example Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/exceptions.md Illustrates raising and catching NoInstallsError, which occurs when attempting operations without any installed Python runtimes. It prompts the user to install one. ```python from manage.exceptions import NoInstallsError try: # When no installs exist raise NoInstallsError() except NoInstallsError as e: print(f"Need to install: {e}") ``` -------------------------------- ### Copy Installation with Hard Links for Duplicates Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/indexutils-fsutils.md Copies an entire installation directory to a target location. For duplicate files within the installation, it uses hard links to save space and improve efficiency. Other files are copied normally. ```python from manage.fsutils import copy, hard_link # Copy entire installation with links for duplicates for file in install_dir.iterdir(): if is_duplicate(file): hard_link(file, target_dir / file.name) else: copy(file, target_dir / file.name) ``` -------------------------------- ### Create Install Aliases and Register in Windows Registry Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/aliasutils-pep514utils.md This snippet demonstrates the common pattern of creating executable aliases and registering a Python installation in the Windows registry after installation. ```python from manage.aliasutils import create_install_aliases from manage.pep514utils import register_install from manage.commands import InstallCommand cmd = InstallCommand(["install", "3.12"]) installs = cmd.get_installs() for install in installs: # Create executable aliases create_install_aliases(install, cmd) # Register in Windows registry register_install(install, cmd.pep514_root) print(f"Setup complete for {install['display-name']}") ``` -------------------------------- ### PyManager CLI: Install Command Source: https://github.com/python/pymanager/blob/main/_autodocs/README.md Use the `py install` command to download and install Python runtimes, specifying the tag, source, and target path. ```bash py install [-s SOURCE] [-f] [-u] [--target=PATH] [--download=PATH] ``` -------------------------------- ### ListCommand Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/commands.md Lists installed Python runtimes with various output formatting options. It can filter results and include unmanaged installations. ```APIDOC ## ListCommand ### Description List installed Python runtimes. ### Command `list []` ### Attributes #### Parameters - **format** (str) - Optional - Output format (table, json, jsonl, csv, exe, prefix, url). Defaults to "table". - **one** (bool) - Optional - Only show first matching result. Defaults to False. - **unmanaged** (bool) - Optional - Include unmanaged installs. Defaults to True. - **source** (str | None) - Optional - Custom index URL. - **default_source** (bool) - Optional - Use install command's default source. ### Example ```python # List all installed runtimes in JSON format cmd = ListCommand(["list", "-f", "jsonl"], root=Path("/opt/pymanager")) cmd.execute() ``` ``` -------------------------------- ### Install Python Versions Source: https://github.com/python/pymanager/blob/main/_autodocs/configuration.md Use the 'py install' command to install specific Python versions. Options allow for forcing reinstallation, specifying an extraction target, downloading packages for offline use, and more. ```bash py install 3.12 # Install latest 3.12 ``` ```bash py install --force 3.12 # Reinstall 3.12 ``` ```bash py install --target=C:\opt\py312 3.12 # Extract instead of install ``` ```bash py install --download=.\cache 3.12 3.13 # Prepare offline packages ``` -------------------------------- ### List Python Installations Source: https://github.com/python/pymanager/blob/main/_autodocs/configuration.md Display installed Python versions. By default, it shows a table of installed versions. ```bash py list 3.12 # Show 3.12 installs ``` -------------------------------- ### InstallCommand Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/commands.md Downloads and installs Python runtimes from a specified source. Supports various options for updating, forcing re-downloads, and dry runs. ```APIDOC ## InstallCommand ### Description Download and install Python runtimes. ### Command `install ` ### Attributes #### Parameters - **source** (str) - Optional - Index JSON URL or path. Defaults to DEFAULT_SOURCE_URL. - **fallback_source** (str | None) - Optional - Fallback index if primary fails. - **target** (Path | None) - Optional - Extract to directory instead of installing. - **download** (Path | None) - Optional - Download only, no installation. - **force** (bool) - Optional - Re-download, overwrite existing. Defaults to False. - **update** (bool) - Optional - Update if newer version available. Defaults to False. - **repair** (bool) - Optional - Repair existing installation. Defaults to False. - **dry_run** (bool) - Optional - Select runtime but don't install. Defaults to False. - **refresh** (bool) - Optional - Update shortcuts and aliases only. Defaults to False. - **by_id** (bool) - Optional - Match TAG against install IDs exactly. Defaults to False. - **automatic** (bool) - Optional - Mark as automatic (internal use). Defaults to False. - **enable_shortcut_kinds** (list[str] | None) - Optional - Enable specific shortcut types. - **disable_shortcut_kinds** (list[str] | None) - Optional - Disable specific shortcut types. ### Example ```python # Install Python 3.12 and update shortcuts cmd = InstallCommand(["install", "--refresh", "3.12"], root=Path("/opt/pymanager")) cmd.execute() ``` ``` -------------------------------- ### Path Example Usage Source: https://github.com/python/pymanager/blob/main/_autodocs/types.md Demonstrates creating a Path object, joining path components using the division operator, and checking if a file exists. ```python from manage.pathutils import Path root = Path("C:\\Python312") exe = root / "python.exe" print(exe) # C:\Python312\python.exe if exe.is_file(): print(f"Found Python at {exe}") ``` -------------------------------- ### Path Class Usage Example Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/pathutils-tagutils-scriptutils.md Demonstrates creating Path objects, joining paths, checking file existence, writing to files, and iterating directory contents. ```python from manage.pathutils import Path root = Path("C:\\Python312") exe = root / "python.exe" if exe.is_file(): print(f"Found: {exe}") config = root / "config.json" config.write_text('{"key": "value"}') for child in root.iterdir(): print(child.name) ``` -------------------------------- ### Package the installer app Source: https://github.com/python/pymanager/blob/main/README.md Produce installer packages (MSIX, APPXSYM, MSI) for the application. This process involves rebuilding the project and requires pymsbuild. ```bash python -m pip install pymsbuild ``` ```bash python make-all.py ``` -------------------------------- ### Get All Installed Python Runtimes Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/installs.md Retrieves a list of all installed Python runtimes, optionally including unmanaged ones and virtual environments. Useful for inventorying available Python versions. ```python def get_installs( install_dir: Path, include_unmanaged: bool = True, virtual_env: Path | str | None = None, ) -> list[dict]: """Retrieve all installed Python runtimes.""" # Function implementation details omitted for brevity ``` ```python from manage.installs import get_installs from manage.pathutils import Path installs = get_installs(Path("C:\\Python\\pkgs"), include_unmanaged=True) for install in installs: print(f"{install['display-name']} at {install['executable']}") ``` -------------------------------- ### Find Installs Matching Tag or Version Range Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/installs.md Use this function to find all installs that match a specific tag or version range. It can optionally return only the first match and include pre-release versions. ```python def get_matching_install_tags( installs: list[dict], tag: str, *, default_platform: str | None = None, single_tag: bool = False, allow_pre: bool = True, ) -> list[tuple[dict, str]] ``` ```python from manage.installs import get_installs, get_matching_install_tags installs = get_installs(Path("C:\\Python\\pkgs")) matches = get_matching_install_tags(installs, "3.12", single_tag=True) if matches: install, tag = matches[0] print(f"Found {install['display-name']}") ``` -------------------------------- ### Install Dictionary Structure Source: https://github.com/python/pymanager/blob/main/_autodocs/README.md Standard Python dictionary structure representing an installed Python runtime. This format is used internally to manage Python installations. ```python { "id": "python-3.12.0-amd64", "display-name": "Python 3.12.0", "company": "PythonCore", "tag": "3.12", "prefix": Path("C:\\Python312"), "executable": Path("C:\\Python312\\python.exe"), "alias": [...], "run-for": [...] } ``` -------------------------------- ### Install pymsbuild Source: https://github.com/python/pymanager/blob/main/README.md Install the pymsbuild tool, which is required for building the project locally. This command should be run before any build or test steps. ```bash python -m pip install pymsbuild ``` -------------------------------- ### Handle NoInstallFoundError Source: https://github.com/python/pymanager/blob/main/_autodocs/errors.md Catch NoInstallFoundError when no installed Python runtime matches the requested tag or script requirements. Access the 'tag' attribute to suggest installation. ```python from manage.exceptions import NoInstallFoundError try: install = cmd.get_install_to_run(tag="3.12") except NoInstallFoundError as e: print(f"Missing Python: {e}") print(f"Tag requested: {e.tag}") # Suggest: py install {e.tag} ``` -------------------------------- ### Install Package Download with Progress Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/indexutils-fsutils.md Downloads a package from a given URL, ensuring the cache directory exists and providing download progress feedback. This is useful for managing package installations with visual progress indication. ```python from manage.indexutils import Index from manage.urlutils import IndexDownloader, urlretrieve from manage.fsutils import ensure_tree, copy # Load index downloader = IndexDownloader(source_url, fallback_source) for index in downloader: version = index.find_to_install("3.12") # Ensure cache exists ensure_tree(cache_dir) # Download with progress dest = cache_dir / version["id"] def progress(pct): print(f"Downloading: {pct}%") urlretrieve( version["url"], dest, on_progress=progress ) ``` -------------------------------- ### Detect and Parse Registry Installs Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/aliasutils-pep514utils.md Finds and parses all Python installations currently registered in the Windows registry. Also shows how to check if a specific install is registered. ```python from manage.pep514utils import find_and_parse_registrations, is_install_registered # Find what's already registered registered = find_and_parse_registrations() for install in registered: print(f"Found: {install['display-name']}") # Check specific install if is_install_registered(my_install): print("Already in registry") ``` -------------------------------- ### List Python Installations in JSON Format Source: https://github.com/python/pymanager/blob/main/_autodocs/configuration.md Output the list of installed Python versions in JSON format using the -f json option. This is helpful for programmatic processing of the output. ```bash py list -f json # JSON output ``` -------------------------------- ### Querying Python Installations Source: https://github.com/python/pymanager/blob/main/_autodocs/README.md Retrieve a list of installed Python runtimes, including unmanaged ones, and print their display names and executable paths. ```python from manage.commands import load_default_config from manage.installs import get_installs cmd = load_default_config(root=Path(".")) installs = cmd.get_installs(include_unmanaged=True) for install in installs: print(f"{install['display-name']} → {install['executable']}") ``` -------------------------------- ### create_install_aliases Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/aliasutils-pep514utils.md Creates all launcher aliases for a given Python installation. It handles creating .exe stubs, naming aliases, respecting configuration, using hard links or copies, and updating PEP 514 registry entries. ```APIDOC ## create_install_aliases ### Description Create all launcher aliases for an installed Python runtime. This function creates launcher .exe stubs in the global directory, names aliases from the install dictionary, respects enable/disable_shortcut_kinds configuration, uses hard links when possible (falling back to copies), and updates PEP 514 registry entries. ### Function Signature ```python def create_install_aliases( install: dict, cmd: BaseCommand, *, dry_run: bool = False, ) -> list[dict] ``` ### Parameters - **install** (dict) - Required - Install dictionary (from installs.get_installs()) - **cmd** (BaseCommand) - Required - Command with configuration and paths - **dry_run** (bool) - Optional - Show what would be done without modifying files (default: False) ### Returns list[dict] - Alias dictionaries created ### Throws - NoLauncherTemplateError - If launcher template not found - OSError - If file operations fail ### Example ```python from manage.aliasutils import create_install_aliases from manage.commands import InstallCommand cmd = InstallCommand(["install", "3.12"]) alias_info = create_install_aliases(install, cmd) for alias in alias_info: print(f"Created: {alias['name']} -> {alias['target']}") ``` ``` -------------------------------- ### List Installed Runtimes Command Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/commands.md Executes the 'list' command to display installed Python runtimes. Supports various output formats and filtering. ```python class ListCommand(BaseCommand): CMD = "list" USAGE_LINE = "list []" ... ``` ```python # List all installed runtimes in JSON format cmd = ListCommand(["list", "-f", "jsonl"], root=Path("/opt/pymanager")) cmd.execute() ``` -------------------------------- ### get_installs Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/installs.md Retrieves a sorted list of all installed Python runtimes, optionally including unmanaged installations and active virtual environments. ```APIDOC ## get_installs ### Description Retrieve all installed Python runtimes. ### Method ```python def get_installs( install_dir: Path, include_unmanaged: bool = True, virtual_env: Path | str | None = None, ) -> list[dict] ``` ### Parameters #### Path Parameters - **install_dir** (Path) - Required - Directory containing managed installations (__install__.json files) - **include_unmanaged** (bool) - Optional - Include Python installs registered in Windows registry. Defaults to True. - **virtual_env** (Path | str | None) - Optional - Path to virtual environment to include in results. Defaults to None. ### Returns list[dict] — Sorted list of install dictionaries **Install Dictionary Structure:** ```python { "id": str, # Unique identifier "display-name": str, # Human-readable name "company": str, # Company/organization "tag": str, # Version tag (e.g., "3.12") "sort-version": Version, # Version for sorting "default": bool, # True if this is the default runtime "prefix": Path, # Installation root directory "executable": Path, # Path to python.exe "executable_args": str | None, # Arguments to pass to executable "unmanaged": bool | None, # True for registry-only installs "alias": list[dict], # Alias entries "run-for": list[dict], # Runtime selection criteria } ``` ### Example ```python from manage.installs import get_installs from manage.pathutils import Path installs = get_installs(Path("C:\\Python\\pkgs"), include_unmanaged=True) for install in installs: print(f"{install['display-name']} at {install['executable']}") ``` ``` -------------------------------- ### Create Synthetic Install Dict for Virtual Environment Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/installs.md Internal function to create a synthetic install dictionary for an active virtual environment. It requires the path to the venv directory and throws an error if pyvenv.cfg is not found or invalid. ```python def _get_venv_install(virtual_env: Path | str) -> dict ``` -------------------------------- ### Clean Old Installation Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/indexutils-fsutils.md Removes old installation directories and cached package files. Includes error handling for cases where files might be in use, suggesting a retry after closing the application. ```python from manage.fsutils import rmtree, unlink # Remove old version try: rmtree(old_install_dir) except FilesInUseError: print("Close Python and retry") # Remove cached package unlink( cache_file, "Cleaning up old download..." ) ``` -------------------------------- ### Refresh All Install Aliases Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/aliasutils-pep514utils.md Updates all existing Python installation aliases. Returns the count of updated aliases. ```python from manage.aliasutils import refresh_install_aliases cmd = InstallCommand(["install", "--refresh"]) count = refresh_install_aliases(cmd) print(f"Updated {count} aliases") ``` -------------------------------- ### Handle InvalidInstallError Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/exceptions.md Demonstrates how to catch and handle an InvalidInstallError, printing the error message and the affected installation path. ```python from manage.exceptions import InvalidInstallError try: raise InvalidInstallError( "Missing python.exe", prefix=Path("C:\\Python312") ) except InvalidInstallError as e: print(f"Broken install: {e}") print(f"At: {e.prefix}") ``` -------------------------------- ### Python API: Entry Point and Find Runtime Source: https://github.com/python/pymanager/blob/main/_autodocs/README.md Use the `main` function as the entry point for the CLI or `find_one` to locate an existing Python runtime without installing it. ```python # Entry point for CLI from manage import main exit_code = main(["py.exe", "install", "3.12"]) # Find runtime without installing from manage import find_one exe, args = find_one( root=Path("."), tag="3.12", script=None, windowed=False, allow_autoinstall=False, show_not_found_error=True, ) ``` -------------------------------- ### Extract User-Friendly Install Alias Names Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/installs.md Extracts user-friendly alias names from install alias dictionaries. It can simplify names by grouping variants and optionally include windowed executables. ```python def get_install_alias_names( aliases: list[dict], friendly: bool = True, windowed: bool = True, ) -> list[str] ``` ```python from manage.installs import get_installs, get_install_alias_names installs = get_installs(Path("C:\\Python\\pkgs")) install = installs[0] names = get_install_alias_names(install["alias"], friendly=True) print(f"Aliases: {names}") # ['python', 'python3', 'python3.12'] ``` -------------------------------- ### register_install Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/aliasutils-pep514utils.md Writes Python installation information to the Windows registry, adhering to PEP 514 standards. It creates necessary subkeys and writes values like InstallPath and ExecutablePath, updating existing entries if present. ```APIDOC ## register_install ### Description Write install information to Windows registry (PEP 514). This function registers a Python installation in the Windows registry by creating Company and Tag subkeys, writing the InstallPath value, and the ExecutablePath if present. It also updates existing entries. ### Function Signature ```python def register_install( install: dict, pep514_root: str | None = None, ) -> None ``` ### Parameters - **install** (dict) - Required - Install dictionary to register - **pep514_root** (str | None) - Optional - Registry key path (default: PEP514_ROOT) ### Behavior - Creates Company and Tag subkeys - Writes InstallPath registry value - Writes ExecutablePath if present - Updates existing entries if present ### Registry Structure Example ``` HKEY_CURRENT_USER\Software\Python\PythonCore\3.12\InstallPath (Default) = C:\Python312 ExecutablePath = C:\Python312\python.exe ``` ### Example ```python from manage.pep514utils import register_install register_install(install) print(f"Registered {install['display-name']} in registry") ``` ``` -------------------------------- ### Minimal pymanager Configuration Source: https://github.com/python/pymanager/blob/main/_autodocs/configuration.md A basic configuration file enabling automatic installation and setting a default Python tag. ```json { "automatic_install": true, "default_tag": "3.12" } ``` -------------------------------- ### tag_or_range Function Examples Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/pathutils-tagutils-scriptutils.md Parses a tag or version range specifier, returning a list of matching tags. ```python from manage.tagutils import tag_or_range tag_or_range("3.12") # ["3.12"] tag_or_range(">=3.11") # ["3.12", "3.13", ...] (if installed) tag_or_range("3.12-64") # ["3.12-64"] tag_or_range("~3.12") # ["3.12.0", "3.12.1", ...] (minor compatible) ``` -------------------------------- ### RunFor Dictionary Examples Source: https://github.com/python/pymanager/blob/main/_autodocs/types.md Specifies runtime selection criteria based on shebang lines. Use this to configure how scripts select a Python interpreter. ```python run_for = { "tag": "3.12", "target": "python.exe", } ``` ```python run_for_windowed = { "tag": "3.12-gui", "target": "pythonw.exe", "windowed": True, } ``` -------------------------------- ### Create Python Launcher Aliases Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/aliasutils-pep514utils.md Creates launcher .exe stubs, respecting configuration and creating hard links or copies as needed. Updates PEP 514 registry entries. Use when installing a new Python runtime to make it available via aliases. ```python from manage.aliasutils import create_install_aliases from manage.commands import InstallCommand cmd = InstallCommand(["install", "3.12"]) alias = {"alias": ["python", "python3"]} aliases = create_install_aliases(alias, cmd) for alias in aliases: print(f"Created: {alias['name']} -> {alias['target']}") ``` -------------------------------- ### List Executable Path Only Source: https://github.com/python/pymanager/blob/main/_autodocs/configuration.md Display only the executable path of the first matching Python installation using -1 and -f exe. Useful for scripting when only the path is needed. ```bash py list -1 -f exe # Executable path only ``` -------------------------------- ### get_matching_install_tags Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/installs.md Finds all installed Python versions that match a given tag or version range. It allows for filtering by platform preference and inclusion of pre-release versions. ```APIDOC ## get_matching_install_tags ### Description Find all installs matching a tag or version range. ### Method ```python def get_matching_install_tags( installs: list[dict], tag: str, *, default_platform: str | None = None, single_tag: bool = False, allow_pre: bool = True, ) -> list[tuple[dict, str]] ``` ### Parameters #### Arguments - **installs** (list[dict]) - Required - List of install dictionaries - **tag** (str) - Required - Tag or version range (e.g., "3.12", ">=3.11", "PythonCore\3") - **default_platform** (str | None) - Optional - Platform preference for selection - **single_tag** (bool) - Optional - Only return first match - **allow_pre** (bool) - Optional - Include pre-release versions ### Returns list[tuple[dict, str]] — List of (install, tag_used) tuples ### Example ```python from manage.installs import get_installs, get_matching_install_tags installs = get_installs(Path("C:\\Python\\pkgs")) matches = get_matching_install_tags(installs, "3.12", single_tag=True) if matches: install, tag = matches[0] print(f"Found {install['display-name']}") ``` ``` -------------------------------- ### companies_match Function Example Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/pathutils-tagutils-scriptutils.md Compares two company names to determine if they refer to the same organization, considering normalization. ```python from manage.tagutils import companies_match companies_match("PythonCore", "CPython") # True companies_match("PythonCore", "") # True companies_match("PyPy", "CPython") # False ``` -------------------------------- ### Index Dictionary Example Source: https://github.com/python/pymanager/blob/main/_autodocs/types.md Represents a parsed Python package index. Use this structure to define available Python versions and their download details. ```python index = { "versions": [ { "id": "python-3.12.0-amd64", "display-name": "Python 3.12.0 (64-bit)", "company": "PythonCore", "tag": "3.12", "url": "https://python.org/ftp/python/3.12.0/python-3.12.0-amd64.exe", "hash": { "sha256": "abc123def456..." }, "sort-version": Version("3.12.0"), } ] } ``` -------------------------------- ### Alias Dictionary Examples Source: https://github.com/python/pymanager/blob/main/_autodocs/types.md Defines a launcher alias or command name for a Python runtime. Use these to map command names to executable targets. ```python alias = { "name": "python.exe", "target": "python.exe", } ``` ```python alias_windowed = { "name": "pythonw.exe", "target": "pythonw.exe", "windowed": True, } ``` -------------------------------- ### ArgumentError Usage Example Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/exceptions.md Demonstrates how to raise and catch the ArgumentError exception. This is useful for handling invalid command-line inputs. ```python from manage.exceptions import ArgumentError try: raise ArgumentError("Unexpected argument: --invalid-flag") except ArgumentError as e: print(f"Invalid arguments: {e}") ``` -------------------------------- ### BaseCommand show_welcome Method Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/commands.md Displays a welcome message, optionally including a copyright notice. This message is shown only once per version if the welcome_on_update flag is true and a new version is detected. ```python def show_welcome(self, copyright: bool = True) -> None ``` -------------------------------- ### CompanyTag Object Example Source: https://github.com/python/pymanager/blob/main/_autodocs/types.md Illustrates the creation and behavior of CompanyTag objects, including normalization and matching. Useful for associating specific Python distributions with tags. ```python from manage.tagutils import CompanyTag tag1 = CompanyTag("PythonCore", "3.12") tag2 = CompanyTag("", "3.12-64") # Both refer to core Python 3.12 print(tag1.company) # "PythonCore" (normalized to empty) ``` -------------------------------- ### Handle AutomaticInstallDisabledError in Python Source: https://github.com/python/pymanager/blob/main/_autodocs/errors.md Catch AutomaticInstallDisabledError to inform the user when auto-installation is disabled and guide them to run the install command manually. ```python from manage.exceptions import AutomaticInstallDisabledError try: exe, args = find_one(...) except AutomaticInstallDisabledError as e: print(f"Auto-install disabled: {e}") # User must manually run: py install ``` -------------------------------- ### HashMismatchError Usage Example Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/exceptions.md Shows how to raise and catch HashMismatchError, typically used after a failed file hash validation. The error message indicates the file was deleted and suggests retrying. ```python from manage.exceptions import HashMismatchError try: raise HashMismatchError() except HashMismatchError as e: print(f"Download corrupted: {e}") ``` -------------------------------- ### Path Operations in Python Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/pathutils-tagutils-scriptutils.md Demonstrates creating paths, joining path components, checking existence, reading file content, and iterating through directory contents. ```python from manage.pathutils import Path # Path creation and joining root = Path("C:\\pymanager") exe = root / "python.exe" # File operations if exe.exists(): content = (root / "config.json").read_text() # Directory iteration for subdir in root.iterdir(): if subdir.is_dir(): print(subdir.name) ``` -------------------------------- ### BaseCommand help Method Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/commands.md Displays help information for the command. It prints global options, command-specific help text, and usage details if it's the base command. ```python def help(self) -> None ``` -------------------------------- ### Complete Uninstall of Python Installation Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/aliasutils-pep514utils.md This snippet shows the process of completely removing a Python installation, including its aliases, registry entry, and installation directory. ```python from manage.aliasutils import remove_install_aliases from manage.pep514utils import unregister_install from manage.fsutils import rmtree cmd = UninstallCommand(["uninstall", "3.12"]) install = installs[0] # Remove aliases remove_install_aliases(install, cmd) # Remove registry entry unregister_install(install, cmd.pep514_root) # Remove installation directory rmtree(install['prefix']) print(f"Removed {install['display-name']}") ``` -------------------------------- ### main Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/manage-main.md Executes the command-line interface with provided arguments. This function serves as the main entry point for the package manager's CLI operations. ```APIDOC ## main ### Description Executes the command-line interface with provided arguments. This function serves as the main entry point for the package manager's CLI operations. ### Method `main` ### Signature ```python def main(args: list[str], root: Path | None = None) -> int ``` ### Parameters #### Path Parameters - **args** (list[str]) - Required - Command-line arguments, including program name as first element - **root** (Path | None) - Optional - Root directory for managing installations. Defaults to sys.prefix ### Returns - **int** — Exit code (0 for success, non-zero for failure) ### Throws - `ArgumentError` — If arguments are invalid - `AutomaticInstallDisabledError` — When automatic installation is disabled but required - `InvalidFeedError` — When package feed is unreachable or malformed - Exception — Generic internal errors; details logged to file ### Example ```python from manage import main import sys # Run as if "py install 3.12" was executed exit_code = main([sys.argv[0], "install", "3.12"]) sys.exit(exit_code) ``` ``` -------------------------------- ### show_help Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/commands.md Displays help information for specified commands. It can optionally take a list of command names to filter the help output. ```APIDOC ## show_help ### Description Display help for command(s). ### Method ```python def show_help(command: list[str] | None = None) -> None ``` ### Parameters #### Path Parameters - **command** (list[str] | None) - Optional - Command name(s) to show help for ### Returns **None** ``` -------------------------------- ### Show Command Help Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/commands.md Displays help information for specified commands. If no command is provided, it may display general help. ```python from manage.commands import show_help # Example of how to call show_help (actual command execution not shown here) # show_help(["install"]) ``` -------------------------------- ### Version Object Usage Source: https://github.com/python/pymanager/blob/main/_autodocs/types.md Demonstrates creating Version objects and performing comparisons. Use this to check version precedence and identify pre-release versions. ```python from manage.verutils import Version v1 = Version("3.12.0") v2 = Version("3.11.5") v3 = Version("3.13.0a1") if v1 > v2: print("3.12 is newer than 3.11") if v3.is_prerelease: print("3.13 is a prerelease") ``` -------------------------------- ### Register Python Install in Windows Registry Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/aliasutils-pep514utils.md Writes Python installation information to the Windows registry, following PEP 514 guidelines. Updates existing entries if present. Use after installing Python to make it discoverable by other tools. ```python from manage.pep514utils import register_install register_install(install) print(f"Registered {install['display-name']} in registry") ``` -------------------------------- ### Show Command Help Source: https://github.com/python/pymanager/blob/main/_autodocs/README.md Displays help information for a specific command. Use this to understand available options and arguments for any pymanager command. ```bash py help [COMMAND] ``` -------------------------------- ### AutomaticInstallDisabledError Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/exceptions.md Raised when automatic installation is required but has been disabled by policy. This prevents Pymanager from automatically installing runtimes. ```APIDOC ## AutomaticInstallDisabledError ### Description Raised when automatic installation is required but disabled by policy. ### Usage ```python from manage.exceptions import AutomaticInstallDisabledError try: raise AutomaticInstallDisabledError() except AutomaticInstallDisabledError as e: print(f"Auto-install blocked: {e}") print(f"Exit with: {e.exitcode}") ``` ### Attributes - **exitcode** (int) - Windows error code `0xA0000006` - **args[0]** (str) - "Automatic installation has been disabled. Please run \"py install\" directly." ### Trigger Conditions - No matching runtime found AND `automatic_install` config is False - No runtimes installed AND `automatic_install` config is False AND `allow_autoinstall` parameter is False - Administrator has disabled auto-install via Group Policy ### Exit Code `0xA0000006` (when caught in `main()`) ``` -------------------------------- ### InvalidInstallError Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/exceptions.md Raised when an installed runtime is corrupted or has missing required files. It indicates issues with the integrity of a Python installation. ```APIDOC ## InvalidInstallError ### Description Raised when an installed runtime is corrupted or has missing required files. ### Usage ```python from manage.exceptions import InvalidInstallError try: raise InvalidInstallError( "Missing python.exe", prefix=Path("C:\\Python312") ) except InvalidInstallError as e: print(f"Broken install: {e}") print(f"At: {e.prefix}") ``` ### Attributes - **prefix** (Path | None) - Installation directory with corrupted files - **args[0]** (str) - Error message ### Trigger Condition Required executable files are missing from installation directory ``` -------------------------------- ### Handle InvalidInstallError in Python Source: https://github.com/python/pymanager/blob/main/_autodocs/errors.md Catch InvalidInstallError to manage problems during PyManager installation. The prefix attribute can indicate the installation directory. ```python from manage.exceptions import InvalidInstallError try: validate_install(install) except InvalidInstallError as e: print(f"Broken install: {e}") if e.prefix: print(f"At: {e.prefix}") # Suggest: py uninstall && py install ``` -------------------------------- ### get_install_to_run Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/commands.md Finds a specific Python runtime to execute based on a tag or script. It can prefer windowed runtimes. ```APIDOC ## get_install_to_run ### Description Find a specific Python runtime to execute. ### Method Signature ```python def get_install_to_run( self, tag: str | None = None, script: str | None = None, *, windowed: bool = False ) -> dict ``` ### Parameters #### Arguments - **tag** (str | None) - Optional - Runtime identifier (e.g., "3.12") - **script** (str | None) - Optional - Script file to analyze #### Keyword Arguments - **windowed** (bool) - Optional - Prefer windowed GUI runtime. Defaults to False. ### Returns - dict — Install dict with "executable" key ### Throws - `NoInstallFoundError` — If no matching install found - `NoInstallsError` — If no installs exist ### Behavior - If script provided without tag, extracts requirements from shebang - Matches tag using fuzzy version matching - Applies platform suffix preference ``` -------------------------------- ### Define InvalidInstallError Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/exceptions.md Defines the InvalidInstallError exception, raised for corrupted or incomplete installations. It includes an optional prefix attribute for the installation directory. ```python class InvalidInstallError(Exception): def __init__(self, message: str, prefix: Path | None = None): ... ``` -------------------------------- ### get_install_to_run Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/installs.md Finds a single Python runtime matching specified criteria, falling back to a default tag if necessary. ```APIDOC ## get_install_to_run ### Description Find a single runtime matching specified criteria. ### Method ```python def get_install_to_run( install_dir: Path, default_tag: str, tag: str | None, *, windowed: bool = False, include_unmanaged: bool = True, virtual_env: Path | str | None = None, default_platform: str | None = None, ) -> dict ``` ### Parameters #### Path Parameters - **install_dir** (Path) - Required - Installation directory - **default_tag** (str) - Required - Default tag if none specified - **tag** (str | None) - Required - Requested tag (e.g., "3.12", ">=3.11") - **windowed** (bool) - Optional - Prefer windowed GUI runtime. Defaults to False. - **include_unmanaged** (bool) - Optional - Include registry installs. Defaults to True. - **virtual_env** (Path | str | None) - Optional - Virtual environment path. Defaults to None. - **default_platform** (str | None) - Optional - Platform preference (e.g., "-64", "-32"). Defaults to None. ### Returns dict — Single install dictionary ### Throws - `NoInstallsError` — If no runtimes are installed - `NoInstallFoundError` — If no runtime matches the criteria ### Example ```python from manage.installs import get_install_to_run from manage.pathutils import Path try: install = get_install_to_run( install_dir=Path("C:\\Python\\pkgs"), default_tag="3", tag="3.12", windowed=False, ) print(f"Execute: {install['executable']}") except NoInstallFoundError as e: print(f"Not found: {e}") ``` ``` -------------------------------- ### Unregister Python Install from Windows Registry Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/aliasutils-pep514utils.md Removes a Python installation's entry from the Windows registry. Silently succeeds if the keys do not exist. ```python from manage.pep514utils import unregister_install unregister_install(install) print(f"Unregistered {install['tag']}") ``` -------------------------------- ### Configure First-Run Checks Source: https://github.com/python/pymanager/blob/main/_autodocs/configuration.md Enable or disable specific first-run checks that occur on startup. Set 'enabled' to false to skip all first-run checks. ```json { "first_run": { "enabled": true, "check_app_alias": true, "check_long_paths": false } } ``` -------------------------------- ### find_and_parse_registrations Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/aliasutils-pep514utils.md Finds all Python installations registered in the Windows registry according to PEP 514. Returns a list of dictionaries, each containing information about a registered Python installation. ```APIDOC ## find_and_parse_registrations ### Description Find all Python installations in Windows registry. This function searches the registry for Python installations conforming to PEP 514 and returns a list of dictionaries, each representing a registered Python install. ### Function Signature ```python def find_and_parse_registrations() -> list[dict] ``` ### Returns list[dict] - Install dictionaries for registered Pythons ### Registry Keys Checked - HKEY_CURRENT_USER\Software\Python\*\InstallPath - HKEY_LOCAL_MACHINE\Software\Python\*\InstallPath ### Example Response Structure ```json { "id": "Registry: {Company}\\{Tag}", "display-name": "{Company} {Tag} ({bitness}-bit)", "company": "str", "tag": "str", "prefix": "Path", "executable": "Path", "unmanaged": True, ... } ``` ### Example ```python from manage.pep514utils import find_and_parse_registrations unmanaged_installs = find_and_parse_registrations() for install in unmanaged_installs: print(f"{install['display-name']} at {install['prefix']}") ``` ``` -------------------------------- ### Retrieve Unmanaged Python Installs from Registry Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/installs.md Internal function to retrieve Python installs that are registered in the Windows registry but not otherwise managed. This is called by the main get_installs function. ```python def _get_unmanaged_installs() -> list[dict] ``` -------------------------------- ### Handle NoInstallsError Source: https://github.com/python/pymanager/blob/main/_autodocs/errors.md Manage NoInstallsError, a special case exit code 0, which signifies that no Python runtimes are currently installed. This error can trigger an automatic install attempt. ```python from manage.exceptions import NoInstallsError try: install = cmd.get_install_to_run() except NoInstallsError as e: print(f"Need to install Python first: {e}") # User should run: py install 3 ``` -------------------------------- ### Tag Matching and Platform Splitting Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/pathutils-tagutils-scriptutils.md Shows how to parse platform information from tags and match version ranges. Includes company normalization for version identifiers. ```python from manage.tagutils import tag_or_range, split_platform # Parse tag with platform tag, plat = split_platform("3.12-64") # Match version range matches = tag_or_range(">=3.11") # All 3.11+ versions installed # Company normalization from manage.tagutils import companies_match if companies_match("PythonCore", "CPython"): print("Same company") ``` -------------------------------- ### Handle NoLauncherTemplateError Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/exceptions.md Demonstrates catching a NoLauncherTemplateError and printing the error message. ```python from manage.exceptions import NoLauncherTemplateError try: raise NoLauncherTemplateError() except NoLauncherTemplateError as e: print(f"Launcher missing: {e}") ``` -------------------------------- ### Load Single Configuration File Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/config.md Loads a single configuration file and merges it into an existing dictionary. Supports an option to overwrite existing values. ```python from manage.config import load_one_config, CONFIG_SCHEMA config = {} load_one_config(config, "pymanager.json", CONFIG_SCHEMA) print(config) # Merged configuration ``` -------------------------------- ### InvalidFeedError Usage Example Source: https://github.com/python/pymanager/blob/main/_autodocs/api-reference/exceptions.md Shows how to raise and catch InvalidFeedError, which signals issues with Python package feeds. The example demonstrates providing a custom message and a feed URL, and accessing the sanitized feed URL from the exception object. ```python from manage.exceptions import InvalidFeedError try: raise InvalidFeedError( message="Network timeout", feed_url="https://www.python.org/ftp/python/index-windows.json" ) except InvalidFeedError as e: print(f"Feed error: {e}") print(f"Feed URL: {e.feed_url}") ```