How to uninstall a package using python-apt and also remove dependencies?

46 Views Asked by At

I want to remove a package using python-apt and also remove all dependendencies. Basically the equivalent to

apt purge PACKAGE
apt autoremove

However I can’t figure out the dependency part. I guess this has to be done using the ProblemResolver class?

Here is my code, that removes a package but does not uninstall dependencies:

import apt

cache = apt.Cache()
resolver = apt.cache.ProblemResolver(cache)
pkg = cache['PACKAGE_NAME']

if pkg.is_installed:
    pkg.mark_delete(True, purge=True)
    
    # does nothing
    resolver.remove(pkg)
    resolver.resolve()
else:
    raise InvalidUsage(package + " is not installed", status_code=400)

try:
    result = cache.commit(allow_unauthenticated=True)
    cache.update()
    cache.open()
except Exception as arg:
    raise Exception(
        "Sorry, purging package failed [{err}]".format(err=str(arg)))

1

There are 1 best solutions below

0
vollstock On

I have implemented a workaround and will share it here.
If anybody could provide a proper solution, I will be very interested :-)

I tried iterating over the dependencies and purging those manually. But this will only remove the direct dependencies. Doing so recursively will remove more packages but far less then what apt autoremove would.

Workaround: ask apt-get shell command to provide a list

So what I did is start a shell command that will provide a list of orphaned packages and iterate over this:

import apt
from subprocess import Popen, PIPE

cache = apt.Cache()
pkg = cache['PACKAGE_NAME']

if pkg.is_installed:
    pkg.mark_delete(purge=True)
else:
    raise InvalidUsage(package + " is not installed", status_code=400)
try:
    result = cache.commit()
    cache.update()
    cache.open()
except Exception as arg:
    raise Exception(
        "Sorry, purging package failed [{err}]".format(err=str(arg)))

dependencies = []

# Now, after package was removed, apt will list autoremovable packages
# https://askubuntu.com/a/652531/873460
ps = Popen("apt-get --dry-run autoremove | grep -Po '^Remv \K[^ ]+'", shell=True, stdout=PIPE)
output = ps.stdout.read()
ps.stdout.close()
ps.wait()
dependencies = output.splitlines()

# mark for removal
for pkg in dependencies:
    cache[pkg.decode()].mark_delete(purge=True)

try:
    cache.commit()
    cache.update()
    cache.open()
except Exception as arg:
    raise Exception(
        "Sorry, purging package failed [{err}]".format(err=str(arg)))