Unverified Commit 31b1271d authored by Massimiliano Adamo's avatar Massimiliano Adamo
Browse files

use python apt instead of subprocess

parent c73747e9
......@@ -15,7 +15,7 @@ Purge unused Ubuntu kernels
### Setup
I havent' created a release process yet.
I did not create a release process yet.
Meanwhile I use Git LFS to upload the package in the folder [deb/](https://gitlab.com/maxadamo/ubuntu-kernel-cleanup/-/tree/master/deb) directory.
......
......@@ -15,7 +15,7 @@ Table of Contents
Setup
I havent’ created a release process yet.
I did not create a release process yet.
Meanwhile I use Git LFS to upload the package in the folder deb/
directory.
......
......@@ -36,24 +36,15 @@ except ModuleNotFoundError as err:
def get_packages_list(pkg_match):
"""
run a shell command like this one:
dpkg --list linux-image-[1-9]* | awk '/^ii /&&/linux-image-/{print $2}'
and create a sorted list of installed kernels.
Or if we need the version only it could be:
dpkg-query -f '${Status} ${Version}\n' -W linux-image-[1-9]* | awk '/ok installed/{print $NF}'
return a list of kernel package versions installed on the system
"""
installed = sp.Popen(
"dpkg --list %s[1-9]* | awk \'/^ii /&&/%s/{print $2}\'" % (
pkg_match, pkg_match),
stdout=sp.PIPE, stderr=sp.PIPE, shell=True
)
installed_out, _ = installed.communicate()
installed_list = installed_out.decode('utf-8').split('\n')
kernels = [x for x in installed_list if x != ''] # delete empty items
kernel_versions = [get_version(item) for item in kernels]
c_list = list(CACHE)
c_list_names = [element.name for element in c_list if CACHE[element].is_installed]
c_list_installed = [element for element in c_list_names if element.startswith(
pkg_match) and any(chr.isdigit() for chr in element)]
c_list_installed_versions = [re.sub(r"(^\D+-|-\D+)", r"", x) for x in c_list_installed]
# sort by version and unique
return natsorted(list(set(kernel_versions)))
return natsorted(c_list_installed_versions)
def process_packages(version_number, prefix, execution_type):
......@@ -165,7 +156,6 @@ if __name__ == '__main__':
# we are running the latest kernel
sanitized_kernel_list = kern_list
del kern_list[-1]
try:
sanitized_kernel_list
except NameError:
......@@ -180,9 +170,9 @@ if __name__ == '__main__':
for kernel_version in purged_list:
process_packages(kernel_version, kernel_pkg, EXECUTION)
CACHE.close() # it returns always true... keeps closing :)
CACHE.close() # it returns always true... keeps closing like swivel doors :)
# purge empty packages
# purge empty packages (it doesn't remove kernel but orphan packages without files)
if EXECUTION == 'real':
CMD = "dpkg-query -f \'${Package} ${Status}\\n\' -W linux-* | awk \'/deinstall ok/{print $1}\' | xargs apt-get purge -y" # pylint: disable=C0301
else:
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment