Skip to content

Commit f024bd9

Browse files
committed
Improved check for already installed library and installation process for the package
1 parent 40c0ab3 commit f024bd9

File tree

2 files changed

+16
-15
lines changed

2 files changed

+16
-15
lines changed

tb_device_mqtt.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -16,20 +16,20 @@
1616
from copy import deepcopy
1717
from inspect import signature
1818
from time import sleep
19-
import importlib.util
19+
from importlib import metadata
2020
from utils import install_package
2121

2222
def check_tb_paho_mqtt_installed():
2323
try:
24-
spec = importlib.util.find_spec("paho.mqtt")
25-
if spec is None:
26-
return False
27-
module_path = spec.origin or "(built-in)"
28-
if 'tb-paho-mqtt-client' in module_path:
29-
return True
30-
else:
31-
return False
32-
except Exception as e:
24+
dists = metadata.distributions()
25+
for dist in dists:
26+
if dist.metadata["Name"].lower() == "tb-paho-mqtt-client":
27+
files = list(dist.files)
28+
for file in files:
29+
if str(file).startswith("paho/mqtt"):
30+
return True
31+
return False
32+
except Exception:
3333
return False
3434

3535
if not check_tb_paho_mqtt_installed():

utils.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,23 +13,24 @@
1313
# limitations under the License.
1414

1515
from sys import executable
16-
from subprocess import check_call, CalledProcessError
16+
from subprocess import check_call, CalledProcessError, DEVNULL
1717
from pkg_resources import get_distribution, DistributionNotFound
1818

1919

2020
def install_package(package, version="upgrade"):
2121
result = False
2222

23-
def try_install(args):
23+
def try_install(args, suppress_stderr=False):
2424
try:
25-
check_call([executable, "-m", "pip", *args])
25+
stderr = DEVNULL if suppress_stderr else None
26+
check_call([executable, "-m", "pip", *args], stderr=stderr)
2627
return True
2728
except CalledProcessError:
2829
return False
2930

3031
if version.lower() == "upgrade":
3132
args = ["install", package, "--upgrade"]
32-
result = try_install(args + ["--user"])
33+
result = try_install(args + ["--user"], suppress_stderr=True)
3334
if not result:
3435
result = try_install(args)
3536
else:
@@ -41,7 +42,7 @@ def try_install(args):
4142
pass
4243
install_version = f"{package}=={version}" if ">=" not in version else f"{package}{version}"
4344
args = ["install", install_version]
44-
if not try_install(args + ["--user"]):
45+
if not try_install(args + ["--user"], suppress_stderr=True):
4546
result = try_install(args)
4647

4748
return result

0 commit comments

Comments
 (0)