apt.cache — The Cache class

The Cache class

class apt.cache.Cache(progress: Optional[OpProgress] = None, rootdir: Optional[str] = None, memonly: bool = False)

Dictionary-like package cache.

The APT cache file contains a hash table mapping names of binary packages to their metadata. A Cache object is the in-core representation of the same. It provides access to APTs idea of the list of available packages.

The cache can be used like a mapping from package names to Package objects (although only getting items is supported).

Keyword arguments: progress – a OpProgress object, rootdir – an alternative root directory. if that is given the system sources.list and system lists/files are not read, only file relative to the given rootdir, memonly – build the cache in memory only.

Changed in version 1.0: The cache now supports package names with special architecture qualifiers such as :all and :native. It does not export them in keys(), though, to keep keys() a unique set.

cache[pkgname]

Return a Package() for the package with the name pkgname.

actiongroup() ActionGroup

Return an ActionGroup object for the current cache.

Action groups can be used to speedup actions. The action group is active as soon as it is created, and disabled when the object is deleted or when release() is called.

You can use the action group as a context manager, this is the recommended way:

with cache.actiongroup():
    for package in my_selected_packages:
        package.mark_install()

This way, the action group is automatically released as soon as the with statement block is left. It also has the benefit of making it clear which parts of the code run with a action group and which don’t.

property broken_count

Return the number of packages with broken dependencies.

cache_post_change() None

called internally if the cache has changed, emit a signal then

cache_pre_change() None

called internally if the cache is about to change, emit a signal then

clear() None

Unmark all changes

close() None

Close the package cache

commit(fetch_progress: Optional[AcquireProgress] = None, install_progress: Optional[InstallProgress] = None, allow_unauthenticated: Optional[bool] = None) bool

Apply the marked changes to the cache.

The first parameter, fetch_progress, refers to a FetchProgress() object as found in apt.progress, the default being apt.progress.FetchProgress().

The second parameter, install_progress, is a apt.progress.InstallProgress() object.

The keyword-only parameter allow_unauthenticated specifies whether to allow unauthenticated downloads. If not specified, it defaults to the configuration option APT::Get::AllowUnauthenticated.

connect(name: str, callback: Union[Callable[[...], None], str]) None

Connect to a signal.

Deprecated since version 1.0: Please use connect2() instead, as this function is very likely to cause a memory leak.

connect2(name: str, callback: Callable[[...], Any], *args: object, **kwds: object) None

Connect to a signal.

The callback will be passed the cache as an argument, and any arguments passed to this function. Make sure that, if you pass a method of a class as your callback, your class does not contain a reference to the cache.

Cyclic references to the cache can cause issues if the Cache object is replaced by a new one, because the cache keeps a lot of objects and tens of open file descriptors.

currently only used for cache_{post,pre}_{changed,open}.

New in version 1.0.

property delete_count

Return the number of packages marked for deletion.

property dpkg_journal_dirty

Return True if the dpkg was interrupted

All dpkg operations will fail until this is fixed, the action to fix the system if dpkg got interrupted is to run ‘dpkg –configure -a’ as root.

fetch_archives(progress: Optional[AcquireProgress] = None, fetcher: Optional[Acquire] = None, allow_unauthenticated: Optional[bool] = None) int

Fetch the archives for all packages marked for install/upgrade.

You can specify either an apt.progress.base.AcquireProgress() object for the parameter progress, or specify an already existing apt_pkg.Acquire object for the parameter fetcher.

The return value of the function is undefined. If an error occurred, an exception of type FetchFailedException or FetchCancelledException is raised.

The keyword-only parameter allow_unauthenticated specifies whether to allow unauthenticated downloads. If not specified, it defaults to the configuration option APT::Get::AllowUnauthenticated.

New in version 0.8.0.

fix_broken() None

Fix broken packages.

get(key: object, default: object = None) Any

Return self*[*key] or default if key not in self.

New in version 1.1.

get_changes() List[Package]

Get the marked changes

get_providing_packages(pkgname: str, candidate_only: bool = True, include_nonvirtual: bool = False) List[Package]

Return a list of all packages providing a package.

Return a list of packages which provide the virtual package of the specified name.

If ‘candidate_only’ is False, return all packages with at least one version providing the virtual package. Otherwise, return only those packages where the candidate version provides the virtual package.

If ‘include_nonvirtual’ is True then it will search for all packages providing pkgname, even if pkgname is not itself a virtual pkg.

has_key(key: object) bool
install_archives(pm: PackageManager, install_progress: InstallProgress) int

The first parameter pm refers to an object returned by apt_pkg.PackageManager().

The second parameter install_progress refers to an InstallProgress() object of the module apt.progress.

This releases a system lock in newer versions, if there is any, and reestablishes it afterwards.

property install_count

Return the number of packages marked for installation.

is_virtual_package(pkgname: str) bool

Return whether the package is a virtual package.

property keep_count

Return the number of packages marked as keep.

keys() List[str]
open(progress: Optional[OpProgress] = None) None

Open the package cache, after that it can be used like a dictionary

property req_reinstall_pkgs

Return the packages not downloadable packages in reqreinst state.

property required_download

Get the size of the packages that are required to download.

property required_space

Get the size of the additional required space on the fs.

update(fetch_progress: Optional[AcquireProgress] = None, pulse_interval: int = 0, raise_on_error: bool = True, sources_list: Optional[str] = None) int

Run the equivalent of apt-get update.

You probably want to call open() afterwards, in order to utilise the new cache. Otherwise, the old cache will be used which can lead to strange bugs.

The first parameter fetch_progress may be set to an instance of apt.progress.FetchProgress, the default is apt.progress.FetchProgress() . sources_list – Update a alternative sources.list than the default. Note that the sources.list.d directory is ignored in this case

upgrade(dist_upgrade: bool = False) None

Upgrade all packages.

If the parameter dist_upgrade is True, new dependencies will be installed as well (and conflicting packages may be removed). The default value is False.

Example

The following example shows how to load the cache, update it, and upgrade all the packages on the system:

import apt
import apt.progress

# First of all, open the cache
cache = apt.Cache()
# Now, lets update the package list
cache.update()
# We need to re-open the cache because it needs to read the package list
cache.open(None)
# Now we can do the same as 'apt-get upgrade' does
cache.upgrade()
# or we can play 'apt-get dist-upgrade'
cache.upgrade(True)
# Q: Why does nothing happen?
# A: You forgot to call commit()!
cache.commit(apt.progress.TextFetchProgress(),
             apt.progress.InstallProgress())

Working with Filters

class apt.cache.Filter

Filter base class

apply(pkg: Package) bool

Filter function, return True if the package matchs a filter criteria and False otherwise

class apt.cache.MarkedChangesFilter

Filter that returns all marked changes

apply(pkg: Package) bool

Filter function, return True if the package matchs a filter criteria and False otherwise

class apt.cache.FilteredCache(cache: Optional[Cache] = None, progress: Optional[OpProgress] = None)

A package cache that is filtered.

Can work on a existing cache or create a new one

filter_cache_post_change() None

Called internally if the cache changes, emit a signal then.

has_key(key: object) bool
keys() KeysView[str]
set_filter(filter: Filter) None

Set the current active filter.

Example

This is an example for a filtered cache, which only allows access to the packages whose state has been changed, eg. packages marked for installation:

>>> from apt.cache import FilteredCache, Cache, MarkedChangesFilter
>>> cache = apt.Cache()
>>> changed = apt.FilteredCache(cache)
>>> changed.set_filter(MarkedChangesFilter())
>>> print(len(changed) == len(cache.get_changes())) # Both need to have same length
True

The ProblemResolver class

class apt.cache.ProblemResolver(cache: Cache)

Resolve problems due to dependencies and conflicts.

The first argument ‘cache’ is an instance of apt.Cache.

clear(package: Package) None

Reset the package to the default state.

protect(package: Package) None

Protect a package so it won’t be removed.

remove(package: Package) None

Mark a package for removal.

resolve() None

Resolve dependencies, try to remove packages where needed.

resolve_by_keep() None

Resolve dependencies, do not try to remove packages.

Exceptions

exception apt.cache.FetchCancelledException

Exception that is thrown when the user cancels a fetch operation.

exception apt.cache.FetchFailedException

Exception that is thrown when fetching fails.

exception apt.cache.LockFailedException

Exception that is thrown when locking fails.