1
0
mirror of https://github.com/home-assistant/core.git synced 2025-12-24 21:06:19 +00:00

Use importlib metadata to check installed packages (#24114)

* Use importlib metadata

* Fix script

* Remove unused import

* Update requirements"
This commit is contained in:
Paulus Schoutsen
2019-05-26 11:58:42 -07:00
committed by GitHub
parent 96b7bb625d
commit 179fb0f3b5
8 changed files with 52 additions and 111 deletions

View File

@@ -5,6 +5,11 @@ import os
from subprocess import PIPE, Popen
import sys
from typing import Optional
from urllib.parse import urlparse
import pkg_resources
from importlib_metadata import version, PackageNotFoundError
_LOGGER = logging.getLogger(__name__)
@@ -16,6 +21,25 @@ def is_virtual_env() -> bool:
hasattr(sys, 'real_prefix'))
def is_installed(package: str) -> bool:
"""Check if a package is installed and will be loaded when we import it.
Returns True when the requirement is met.
Returns False when the package is not installed or doesn't meet req.
"""
try:
req = pkg_resources.Requirement.parse(package)
except ValueError:
# This is a zip file. We no longer use this in Home Assistant,
# leaving it in for custom components.
req = pkg_resources.Requirement.parse(urlparse(package).fragment)
try:
return version(req.project_name) in req
except PackageNotFoundError:
return False
def install_package(package: str, upgrade: bool = True,
target: Optional[str] = None,
constraints: Optional[str] = None) -> bool: