Created
April 22, 2019 20:42
-
-
Save yunqu/25d8547418a03a0fb22e8f3e51913006 to your computer and use it in GitHub Desktop.
Code to check OS package in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
import shutil | |
import subprocess | |
rootfs_packages = { | |
'jupyter': '4.4', | |
'python3-opencv': '3.2.0', | |
'lm-sensors': '1' | |
} | |
# Convert version number | |
def convert_version(version): | |
while version.count('.') < 2: | |
version += '.0' | |
version_temp = [int(x, 10) for x in version.split('.')] | |
version_temp.reverse() | |
return sum(x * (100 ** i) for i, x in enumerate(version_temp)) | |
# Check available command for packaging tool | |
def get_package_tool(): | |
for i in ['apt', 'rpm']: | |
if shutil.which(i) is not None: | |
return i | |
return None | |
# For apt tool | |
def find_apt_package(package_name): | |
command = 'apt-cache show {} | grep Version'.format(package_name) | |
output = subprocess.Popen(command, shell=True, | |
stdout=subprocess.PIPE, stderr=subprocess.STDOUT) | |
ret = output.communicate()[0].decode("utf-8") | |
version_match = re.search(r"^Version: ([0-9\.]*)", ret, re.M) | |
return version_match | |
# For rpm tool | |
def find_rpm_package(package_name): | |
command = 'rpm -qa | grep {}'.format(package_name) | |
output = subprocess.Popen(command, shell=True, | |
stdout=subprocess.PIPE, stderr=subprocess.STDOUT) | |
ret = output.communicate()[0].decode("utf-8") | |
version_match = re.search(r"^{}-([0-9\.]*)-*".format(package_name), | |
ret, re.M) | |
return version_match | |
# Check minimum version. If the package is bootstrapped, we can ignore this | |
def check_min_package(package_name): | |
min_version = rootfs_packages[package_name] | |
pkg_tool = get_package_tool() | |
if pkg_tool == 'apt': | |
version_match = find_apt_package(package_name) | |
elif pkg_tool == 'rpm': | |
version_match = find_apt_package(package_name) | |
else: | |
raise EnvironmentError("Linux flavor is not supported.") | |
if version_match: | |
found_version = convert_version(version_match.group(1)) | |
else: | |
raise EnvironmentError("Package {0} is missing. Use {1} to " | |
"install it".format(package_name, pkg_tool)) | |
if found_version < convert_version(min_version): | |
raise EnvironmentError("Minimum required version for {0} is " | |
"{1}".format(package_name, min_version)) | |
check_min_package('lm-sensors') | |
check_min_package('jupyter') | |
check_min_package('python3-opencv') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment