1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
# SPDX-FileCopyrightText: Copyright 2022, Arm Limited and/or its affiliates.
# SPDX-License-Identifier: Apache-2.0
"""Util functions for managing python packages."""
from __future__ import annotations
import sys
from importlib.metadata import distribution
from importlib.metadata import PackageNotFoundError
from subprocess import check_call # nosec
class PyPackageManager:
"""Python package manager."""
@staticmethod
def package_installed(pkg_name: str) -> bool:
"""Return true if package installed."""
try:
distribution(pkg_name)
except PackageNotFoundError:
return False
return True
def packages_installed(self, pkg_names: list[str]) -> bool:
"""Return true if all provided packages installed."""
return all(self.package_installed(pkg) for pkg in pkg_names)
def install(self, pkg_names: list[str]) -> None:
"""Install provided packages."""
if not pkg_names:
raise ValueError("No package names provided")
self._execute_pip_cmd("install", pkg_names)
def uninstall(self, pkg_names: list[str]) -> None:
"""Uninstall provided packages."""
if not pkg_names:
raise ValueError("No package names provided")
self._execute_pip_cmd("uninstall", ["--yes", *pkg_names])
@staticmethod
def _execute_pip_cmd(subcommand: str, params: list[str]) -> None:
"""Execute pip command."""
assert sys.executable, "Unable to launch pip command"
check_call(
[
sys.executable,
"-m",
"pip",
"--disable-pip-version-check",
subcommand,
*params,
]
)
def get_package_manager() -> PyPackageManager:
"""Get python packages manager."""
return PyPackageManager()
|