Skip to content

Commit

Permalink
Add: the function of installing and checking third-party libraries
Browse files Browse the repository at this point in the history
  • Loading branch information
mjq2020 committed Nov 9, 2023
1 parent 1a9c232 commit 9e21986
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 1 deletion.
14 changes: 13 additions & 1 deletion sscma/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,17 @@
from .config import load_config
from .inference import Infernce
from .iot_camera import IoTCamera
from .check import net_online, install_lib, check_lib

__all__ = ['NMS', 'xywh2xyxy', 'xyxy2cocoxywh', 'load_image', 'load_config', 'Infernce', 'IoTCamera']
__all__ = [
'NMS',
'xywh2xyxy',
'xyxy2cocoxywh',
'load_image',
'load_config',
'Infernce',
'IoTCamera',
'net_online',
'install_lib',
'check_lib',
]
66 changes: 66 additions & 0 deletions sscma/utils/check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
from typing import Optional, Union, Iterable
import subprocess


def net_online() -> bool:
"""
Check whether the current device is connected to the Internet.
"""
import socket

for host in '1.1.1.1', '8.8.8.8', '223.5.5.5': # Cloudflare, Google, AliDNS:
try:
test_connection = socket.create_connection(address=(host, 53), timeout=2)
except (socket.timeout, socket.gaierror, OSError):
continue
else:
# If the connection was successful, close it to avoid a ResourceWarning
test_connection.close()
return True
return False


def install_lib(name: Union[str, Iterable[str]], version: Optional[Union[str, Iterable[str]]] = None) -> bool:
"""Install python third-party libraries."""
if isinstance(name, str):
name = [name]
if version is not None:
if isinstance(version, str):
name = [i + version for i in name]
else:
name = [i + version[idx] for idx, i in enumerate(name)]

if version is not None:
name = '=='.join(name)
try:
assert net_online(), "Network Connection Failure!"
print(f"Third-party library {name} being installed")
subprocess.check_output(f'pip install --no-cache {name}', shell=True).decode()
return True
except Exception as e:
print(f"Warning ⚠️: Installation of {name} has failed, the installation process has been skipped")
return False


def check_lib(name: str, version: Optional[str] = None, install: bool = True) -> bool:
"""
Check if the third-party libraries have been installed.
"""
import pkg_resources as pkg

flag = True
try:
pkg.require(name)
except pkg.DistributionNotFound:
try:
import importlib

importlib.import_module(next(pkg.parse_requirements(name)).name)
except ImportError:
flag = False
except pkg.VersionConflict:
pass

if install and not flag:
return install_lib(name, version=version)
return flag

0 comments on commit 9e21986

Please sign in to comment.