PipInstaller
Base classes
| Name |
Children |
Inherits |
PackageInstaller anyenv.package_install.base Base class for package installer implementations. |
|
|
â‹” Inheritance diagram
graph TD
597138884["pip_install.PipInstaller"]
2807983507["base.PackageInstaller"]
925645236["abc.ABC"]
2751680898["builtins.object"]
2807983507 --> 597138884
925645236 --> 2807983507
2751680898 --> 925645236
🛈 DocStrings
Bases: PackageInstaller
Package installer using pip.
Source code in src/anyenv/package_install/pip_install.py
| class PipInstaller(PackageInstaller):
"""Package installer using pip."""
async def install(
self,
package_name: str,
version: str | None = None,
upgrade: bool = False,
) -> None:
"""Install a package using pip.
Args:
package_name: Name of the package to install.
version: Optional version specifier.
upgrade: Whether to upgrade an existing package.
"""
# Format the package name with version if specified
if version:
if version[0] not in ("=", "<", ">", "!"):
version = "==" + version
package_spec = f"{package_name}{version}"
else:
package_spec = package_name
# Build the command
args = ["install", package_spec]
if upgrade:
args.append("--upgrade")
# Run pip in a separate process to avoid blocking the event loop
cmd = [sys.executable, "-m", "pip", *args]
print(f"Running: {' '.join(cmd)}")
# Use anyio's run_process
import subprocess
import anyio
try:
# When check=True, run_process raises CalledProcessError on non-zero exit
process = await anyio.run_process(cmd, check=True)
# Output is available in process.stdout
print(process.stdout.decode())
# Reload the package if it was upgraded
if upgrade:
self._reload_package(package_name)
except subprocess.CalledProcessError as e:
error_msg = e.stderr.decode() if e.stderr else str(e)
msg = f"Pip installation failed: {error_msg}"
raise RuntimeError(msg) from e
def _reload_package(self, package_name: str) -> None:
"""Attempt to reload a package's modules after installation."""
try:
dist = importlib.metadata.distribution(package_name)
if top_level_content := dist.read_text("top_level.txt"):
top_level_modules = top_level_content.splitlines()
for mod in top_level_modules:
if mod not in sys.modules:
continue
try:
importlib.reload(sys.modules[mod])
except Exception as e: # noqa: BLE001
print(f"Warning: Failed to reload module {mod}: {e}")
except Exception as e: # noqa: BLE001
print(f"Warning: Failed to reload package {package_name}: {e}")
|
install
async
install(package_name: str, version: str | None = None, upgrade: bool = False) -> None
Install a package using pip.
Parameters:
| Name |
Type |
Description |
Default |
package_name
|
str
|
Name of the package to install.
|
required
|
version
|
str | None
|
Optional version specifier.
|
None
|
upgrade
|
bool
|
Whether to upgrade an existing package.
|
False
|
Source code in src/anyenv/package_install/pip_install.py
| async def install(
self,
package_name: str,
version: str | None = None,
upgrade: bool = False,
) -> None:
"""Install a package using pip.
Args:
package_name: Name of the package to install.
version: Optional version specifier.
upgrade: Whether to upgrade an existing package.
"""
# Format the package name with version if specified
if version:
if version[0] not in ("=", "<", ">", "!"):
version = "==" + version
package_spec = f"{package_name}{version}"
else:
package_spec = package_name
# Build the command
args = ["install", package_spec]
if upgrade:
args.append("--upgrade")
# Run pip in a separate process to avoid blocking the event loop
cmd = [sys.executable, "-m", "pip", *args]
print(f"Running: {' '.join(cmd)}")
# Use anyio's run_process
import subprocess
import anyio
try:
# When check=True, run_process raises CalledProcessError on non-zero exit
process = await anyio.run_process(cmd, check=True)
# Output is available in process.stdout
print(process.stdout.decode())
# Reload the package if it was upgraded
if upgrade:
self._reload_package(package_name)
except subprocess.CalledProcessError as e:
error_msg = e.stderr.decode() if e.stderr else str(e)
msg = f"Pip installation failed: {error_msg}"
raise RuntimeError(msg) from e
|
:fa-brands-github: Show source on GitHub