apt_pkg - Classes and functions wrapping the apt-pkg library.
| Use Case | Command | Description |
|---|---|---|
| ποΈ Open package cache | cache = apt_pkg.Cache(progress) | Load APT cache, optionally with progress reporting |
| π Access a package | pkg = cache['apt'] | Get a Package object by name (or tuple name, arch) |
| π¦ List all packages | for pkg in cache.packages: | Iterate over every package in the cache |
| βοΈ Mark for install | depcache.mark_install(pkg) | Mark a package for installation (with auto_inst, from_user) |
| ποΈ Mark for removal | depcache.mark_delete(pkg, purge=True) | Mark package for deletion (or purging) |
| β Commit changes | depcache.commit(acquire_progress, install_progress) | Fetch and install marked packages |
| π§ Read configuration | val = apt_pkg.config.find('APT::Get::Assume-Yes') | Retrieve a configuration value with optional default |
| π Parse dependencies | deps = apt_pkg.parse_depends('apt (>= 1.0)') | Return parsed dependency lists |
| π System lock | with apt_pkg.SystemLock(): | Context manager for global dpkg/apt lock |
| π₯ Fetch files | acquire = apt_pkg.Acquire(progress) | Coordinate network/copy file retrieval |
The apt_pkg module provides several classes and functions for accessing the functionality provided by the apt-pkg library. Typical uses might include reading APT index files and configuration files and installing or removing packages.
_PackageManager(builtins.object) β PackageManager
builtins.SystemError(builtins.Exception) β Error
builtins.ValueError(builtins.Exception) β CacheMismatchError
builtins.object
Acquire
AcquireItem β AcquireFile
AcquireItemDesc
AcquireWorker
ActionGroup
Cache
Cdrom
Configuration
DepCache
Dependency
DependencyList
Description
FileLock
Group
GroupList
HashString
HashStringList
Hashes
IndexFile
MetaIndex
OrderList
Package
PackageFile
PackageList
PackageRecords
Policy
ProblemResolver
SourceList
SourceRecordFiles
SourceRecords
SystemLock
Tag β TagRemove, TagRename, TagRewrite
TagFile
TagSection
Version
Acquire([progress: apt.progress.base.AcquireProgress])
π₯ Coordinate file retrieval via network or local (copy:/). Optional progress object reports progress.
get_lock(log: str) β π Acquire a lock for the given directory.run() -> int β βΆοΈ Run the fetcher; returns RESULT_CANCELLED, RESULT_CONTINUE, or RESULT_FAILED.shutdown() β π Shut down the fetcher, removing all items.π Data descriptors:
fetch_needed β π¦ Total bytes to fetch.items β π List of AcquireItem objects.partial_present β β³ Bytes already available.total_needed β π Total bytes needed (fetched + to fetch).workers β π· Active AcquireWorker objects.π·οΈ Constants:
RESULT_CANCELLED = 2RESULT_CONTINUE = 0RESULT_FAILED = 1
AcquireFile(owner, uri[, hash, size, descr, short_descr, destdir, destfile])
π₯ Represent a file to be fetched. Owner is an Acquire object. Optional parameters for hashes, size, descriptions, and destination.
Inherits from AcquireItem. See that class for common descriptors.
β Cannot be instantiated directly; use AcquireFile.
π Data descriptors:
active_subprocess β π Active subprocess name (e.g., 'gzip', 'rred', 'gpgv').complete β β
Whether the item was fetched completely.desc_uri β π URI description.destfile β π Destination file path.error_text β β Error string if any.filesize β π File size in bytes.id β π’ Integer ID.is_trusted β π True if from a trusted repository.local β π True if fetching a local item (copy:/).mode β βͺ Old name for active_subprocess.partialsize β π Bytes fetched so far.status β π¦ Status; compare with STAT_* constants.π·οΈ Constants:
STAT_AUTH_ERROR = 4STAT_DONE = 2STAT_ERROR = 3STAT_FETCHING = 1STAT_IDLE = 0STAT_TRANSIENT_NETWORK_ERROR = 5π Provide description and URI of an item. Used by progress classes.
π Data descriptors:
description β π Long description.owner β π€ The owning AcquireItem.shortdesc β π Short description (e.g., package name).uri β π The URI to download from.
π· Represent a sub-process fetching files using methods from Dir::Bin::Methods.
π Data descriptors:
current_item β π¦ Currently fetched AcquireItemDesc.current_size β π Fetched bytes for current item.resumepoint β β³ Bytes already available when download started.status β π¦ Worker status string.total_size β π Total size of current item.
ActionGroup(depcache)
β‘ Disable cleanup actions for faster batch modifications. Use as context manager or call release(). Example:
with apt_pkg.ActionGroup(depcache):
depcache.markInstall(pkg)
release() β π End the action group; triggers deferred cleanup if last group.
Cache([progress]) -> Cache() object.
π Inβcore representation of the APT cache. Provides access to available packages, mapping names to Package objects. Optional progress for loading.
update(progress, sources: SourceList, pulse_interval: int) -> bool β π Fetch updated index files; does not affect current cache.__contains__, __getitem__, __len__ β π Dictionary-like access.π Data descriptors:
depends_count β π Number of dependency objects.file_list β π List of PackageFile objects.group_count β π¦ Number of Group objects.groups β π List of Group objects.is_multi_arch β π Whether multi-arch is supported.package_count β π Number of packages.package_file_count β π Number of package files.packages β π¦ List of Package objects.policy β π― The Policy for this cache.provides_count β π Number of Provides relations.ver_file_count β π (Version, PackageFile) relations.version_count β π·οΈ Number of Version objects.
β Raised when an object from a different cache is passed to DepCache methods. Inherits from ValueError.
Cdrom()
πΏ Identify and add Debian installation media to /etc/apt/sources.list.
add(progress: apt_pkg.CdromProgress) -> bool β β Add CD-ROM to sources.ident(progress: apt_pkg.CdromProgress) -> str β π Return hexadecimal CD-ROM ID (or None).
Configuration()
π§ Map option keys to values, reading from config files. The global apt_pkg.config is the most important instance.
clear(key: str) β π§Ή Remove option and all sub-options.dump() -> str β π Return a string dump of the configuration.exists(key: str) -> bool β β Check if key exists.find(key: str[, default: str = '']) -> str β π Return value or default.find_b(key: str[, default: bool = False]) -> bool β β
Boolean variant.find_dir(key: str[, default: str = '']) -> str β π Like find_file but adds trailing slash.find_file(key: str[, default: str = '']) -> str β π Resolve filename with directory prefixes.find_i(key: str[, default: int = 0]) -> int β π’ Integer variant.get(key[, default]) -> str β π Same as find.keys([root: str]) -> list β π All keys below root.list([root: str]) -> list β π All items at root, full names.my_tag() -> str β π·οΈ Tag of the root (empty for global).set(key: str, value: str) β βοΈ Set key to value.subtree(key: str) -> apt_pkg.Configuration β π³ Return a sub-configuration rooted at key.value_list([root: str]) -> list β π Values instead of keys.
DepCache(cache: apt_pkg.Cache)
π¦ Holds extra state on packages: marks, broken status, etc. Required for package manipulation.
commit(acquire_progress, install_progress) β β
Fetch and install marked changes.fix_broken() -> bool β π§ Attempt to fix broken packages.get_candidate_ver(pkg: apt_pkg.Package) -> apt_pkg.Version β π― Get the candidate version.init(progress: apt.progress.base.OpProgress) β π (Re)initialize the depcache.is_auto_installed(pkg) -> bool β π€ Check if automatically installed.is_garbage(pkg) -> bool β ποΈ Check if autoβinstalled and no longer needed.is_inst_broken(pkg) -> bool β β Broken ignoring marked changes.is_now_broken(pkg) -> bool β β Broken including marked changes.is_upgradable(pkg) -> bool β β¬οΈ Upgradable?mark_auto(pkg, auto: bool) β π·οΈ Mark as automatically installed or not.mark_delete(pkg[, purge: bool = False]) β ποΈ Mark for deletion/purging.mark_install(pkg[, auto_inst=True, from_user=True]) β β¬οΈ Mark for installation.mark_keep(pkg) β π Mark to keep current version.marked_delete(pkg) -> bool β β Marked for removal?marked_downgrade(pkg) -> bool β β¬οΈ Marked for downgrade?marked_install(pkg) -> bool β β¬οΈ Marked for install?marked_keep(pkg) -> bool β π Should be kept?marked_reinstall(pkg) -> bool β π Marked for reinstall?marked_upgrade(pkg) -> bool β β¬οΈ Marked for upgrade?minimize_upgrade() -> bool β π Keep each package marked for upgrade if possible.read_pinfile([file: str]) β π Read pin policy.set_candidate_release(pkg, ver, rel: string) -> bool β π― Set candidate version and align dependencies to a release.set_candidate_ver(pkg, ver) -> bool β π― Set candidate version.set_reinstall(pkg, reinstall: bool) β π Mark for reinstall.upgrade([dist_upgrade: bool = True]) -> bool β β¬οΈ Mark packages for upgrade (dist-upgrade if true).π Data descriptors:
broken_count β β Number of broken packages.deb_size β π¦ Total download size for changes.del_count β ποΈ Packages marked for removal.inst_count β β¬οΈ Packages marked for install.keep_count β π Packages marked for keep.policy β π― The Policy object.usr_size β πΎ Disk space change (Installed-Size delta).π Represent a dependency from one package version to a package, optionally with a version relation.
all_targets() -> list β π― All Version objects satisfying this dependency.π Data descriptors:
comp_type β π’ Comparison operator in mathematical notation: <, <=, =, !=, >=, >, ''.comp_type_deb β π’ Debian notation: <<, <=, =, !=, >=, >>, ''.dep_type β π·οΈ Translated dependency type string.dep_type_enum β π’ Numeric type; compare with TYPE_* constants.dep_type_untranslated β π·οΈ Untranslated type string.id β π’ Numeric ID.parent_pkg β π€ Dependent package.parent_ver β π€ Dependent version.target_pkg β π― Package depended upon.target_ver β π― Version string of target.π·οΈ Constants:
TYPE_CONFLICTS = 5TYPE_DEPENDS = 1TYPE_DPKG_BREAKS = 8TYPE_ENHANCES = 9TYPE_OBSOLETES = 7TYPE_PREDEPENDS = 2TYPE_RECOMMENDS = 4TYPE_REPLACES = 6TYPE_SUGGESTS = 3
π Efficient list-like type for Dependency objects. Supports __getitem__ and __len__.
π Represent a package description and attributes (e.g., for translations).
π Data descriptors:
file_list β π List of PackageFile objects.language_code β π Language code (empty for untranslated).md5 β π MD5 hash of the description.
β Exception class for most python-apt exceptions. Inherits from SystemError (catch this first). Introduced in 1.1.
SystemLock(filename: str)
π Context manager for file-based locking. Usage:
with apt_pkg.FileLock(filename):
...
__enter__ β π Lock the file.__exit__ β π Release the lock.
Group(cache, name)
π¦ Group of packages sharing the same name. Supports iteration and find_package(architecture), find_preferred_package(prefer_non_virtual=True).
π Efficient internal representation for the groups attribute of Cache. Supports __getitem__ and __len__.
HashString(type, hash) or HashString('type:hash')
π Store a hash and its type (MD5Sum, SHA1, SHA256). Supports comparison operators and verify_file(filename).
π Data descriptors:
hashtype β π·οΈ Hash type string.hashvalue β π’ Hexadecimal hash string.usable β β
Whether the hash is trusted.
HashStringList()
π Manage a list of HashString objects. Knows the best hash and provides verify_file(filename).
append(object: HashString) β β Append a hash.find(type: str = "") -> HashString β π Find a hash of the given type, or the best one.verify_file(filename: str) -> bool β β
Verify all hashes in the list.π Data descriptors:
file_size β π File size if part of the list, else 0.usable β β
Whether at least one trusted hash is present.
Hashes([object: (bytes, file)])
π Calculate all supported hashes for a given object (bytes, file descriptor, or file-like with fileno()).
π Data descriptors:
hashes β π A HashStringList of all computed hashes.π Represent an index file (package indexes, translation indexes, source indexes).
archive_uri(path: str) -> str β π Return the URI for a given path in the archive.π Data descriptors:
describe β π Description string.exists β β
Whether the file exists.has_packages β π¦ Whether it contains packages.is_trusted β π Whether it can be trusted (GPG signed Release).label β π·οΈ Label.size β π Size in bytes.
π Provide information about meta-indexes (Release files): trusted status, URI, distribution, and list of IndexFile objects.
π Data descriptors:
dist β π¦ Distribution string.index_files β π List of IndexFile objects.is_trusted β π Trusted?uri β π URI of the meta index.
OrderList(depcache: DepCache)
π Sequence type for packages with ordering methods for configuration and unpacking.
append(pkg: Package) β β Append a package.flag(pkg: Package, flag: int[, unset_flags: int]) β π Set/clear flags.is_flag(pkg: Package, flag: int) β β Check flag(s).is_missing(pkg: Package) β β Check if package is marked for install.is_now(pkg: Package) β β Check if package is flagged for any state but removal.order_configure() β π§ Order for configuration (Policy).order_critical() β β‘ Order by PreDepends only (critical unpack).order_unpack() β π¦ Order for unpacking.score(pkg: Package) -> int β π Return the score.wipe_flags(flags: int) β π§Ή Remove flags from all packages.π·οΈ Flags:
FLAG_ADDED = 1FLAG_ADD_PENDIG = 2FLAG_AFTER = 256FLAG_CONFIGURED = 32FLAG_IMMEDIATE = 4FLAG_IN_LIST = 128FLAG_LOOP = 8FLAG_REMOVED = 64FLAG_STATES_MASK = 112FLAG_UNPACKED = 16
π¦ Represent a package. Access versions via version_list, and manipulate with DepCache.
get_fullname([pretty: bool = False]) -> str β π Full name including architecture; omit arch for native if pretty=True.π Data descriptors:
architecture β ποΈ Architecture.current_state β π¦ Current state (compare with CURSTATE_*).current_ver β π·οΈ Currently installed version, or None.essential β β Essential flag.has_provides β π Whether provided by another package.has_versions β π¦ Whether any version exists in the cache.id β π’ Numeric ID.important β β Old 'Important' flag.inst_state β π¦ Install state (compare with INSTSTATE_*).name β π Package name.provides_list β π List of (providesname, providesver, version) tuples.rev_depends_list β π Reverse dependencies (DependencyList).selected_state β π¦ Selection state (compare with SELSTATE_*).version_list β π List of Version objects.π An index file stored in the cache with extra metadata.
π Data descriptors:
architecture β ποΈ Architecture (unused, empty).archive β π¦ Archive (Suite) from Release.codename β π·οΈ Codename (e.g., squeeze-updates).component β π§© Component (e.g., 'main').filename β π Path to the file.id β π’ Numeric ID.index_type β π·οΈ Type string (e.g., 'Debian Package Index').label β π·οΈ Label from Release.not_automatic β π« NotAutomatic flag.not_source β π« Lacks an active source (packages cannot be downloaded).origin β π Origin from Release.site β π Hostname of the source.size β π Size in bytes.version β π·οΈ Version from Release (e.g., '5.0.X').
π Efficient internal representation for the packages attribute of Cache. Supports __getitem__ and __len__.
PackageManager(depcache: apt_pkg.DepCache)
π¦ Fetch and install packages marked in the depcache. Override methods to implement custom behavior.
configure(pkg: Package) -> bool β βοΈ Add a configure action.go(status_fd: int) -> bool β βΆοΈ Start dpkg.install(pkg: Package, filename: str) -> bool β β¬οΈ Add an install action.remove(pkg: Package, purge: bool) -> bool β ποΈ Add a removal action.reset() β π Reset for a new round.do_install(status_fd: int) -> int β π Install packages; returns RESULT_COMPLETED, RESULT_FAILED, RESULT_INCOMPLETE.fix_missing() -> bool β π§ Fix missing packages.get_archives(fetcher: Acquire, list: SourceList, recs: PackageRecords) -> bool β π₯ Queue downloads.π·οΈ Constants:
RESULT_COMPLETED = 0RESULT_FAILED = 1RESULT_INCOMPLETE = 2
PackageRecords(cache: apt_pkg.Cache)
π Retrieve package metadata like maintainer, filename, hashes, and raw record.
lookup((packagefile: apt_pkg.PackageFile, index: int)) -> bool β π Change to a new package.π Data descriptors:
filename β π Filename field.hashes β π HashStringList.homepage β π Homepage field.long_desc β π Long description.maintainer β π€ Maintainer field.md5_hash β π MD5 hash.name β π Package name.record β π Raw record (for TagSection).sha1_hash β π SHA1 hash.sha256_hash β π SHA256 hash.short_desc β π Short description.source_pkg β π¦ Source package name (if different).source_ver β π·οΈ Source package version.
Policy(cache)
π― Representation of the cache policy; creates pins, reads pin files, and overrides priorities.
create_pin(type: str, pkg: str, data: str, priority: int) β π Create a pin (type: 'Version', 'Release', 'Origin').get_candidate_ver(package: apt_pkg.Package) -> Optional[apt_pkg.Version] β π― Get the best version.get_priority(package: Union[apt_pkg.Package, apt_pkg.Version, apt_pkg.PackageFile]) -> int β π’ Return priority.init_defaults() β π Initialize defaults after create_pin() with empty pkg.read_pindir(dirname: str) -> bool β π Read pin files from directory.read_pinfile(filename: str) -> bool β π Read a single pin file.set_priority(which, priority: int) β π― Override priority for a version/file.
ProblemResolver(depcache: apt_pkg.DepCache)
π§ Resolve dependency problems by marking packages for installation/removal.
clear(pkg: apt_pkg.Package) β π Revert protect/remove actions.protect(pkg: apt_pkg.Package) β π‘οΈ Mark as protected (state won't change).remove(pkg: apt_pkg.Package) β ποΈ Mark for removal.resolve([fix_broken: bool = True]) -> bool β π§ Intelligently resolve problems.resolve_by_keep() -> bool β π Try to resolve only by keeping packages.
SourceList()
π Represent the list of sources from /etc/apt/sources.list and similar files.
find_index(pkgfile: apt_pkg.PackageFile) -> apt_pkg.IndexFile β π Find the index file for a given package file.get_indexes(acquire: apt_pkg.Acquire[, all: bool=False]) -> bool β π₯ Add indexes (Release, Packages) to an Acquire object.read_main_list() -> bool β π Read/refresh the source list.π Data descriptors:
list β π List of MetaIndex objects.
SourceRecordFile()
π Look up source package file records. Supports __getitem__ and __len__.
π Data descriptors:
hashes β π HashStringList of the source file.path β π Remote path.size β π Size.type β π·οΈ Type of the source file.
SourceRecords()
π Look up source package records. Iterate with lookup() or step().
lookup(name: str) -> bool β π Look up a source package by name.restart() β π Restart the parser.step() -> bool β βοΈ Move to the next source package.π Data descriptors:
binaries β π List of binary package names.build_depends β π§ Build dependencies (dict, same format as depends_list_str).files β π List of SourceRecordFiles objects.index β π List of IndexFile objects.maintainer β π€ Maintainer.package β π Source package name.record β π Raw record.section β π·οΈ Section.version β π·οΈ Version.
SystemLock()
π Context manager for the global dpkg/apt lock. Usage:
with apt_pkg.SystemLock():
...
__enter__ β π Lock the system.__exit__ β π Release the lock.
π·οΈ Abstract base for actions on a tag section. Subclasses: TagRemove, TagRename, TagRewrite.
π Data descriptors:
action β π¬ Action to perform (0=REMOVE, 1=RENAME, 2=REWRITE).data β π Data for rewrite or new name for rename.name β π Tag name to act on.π·οΈ Constants:
REMOVE = 0RENAME = 1REWRITE = 2
TagRemove(name: str) β ποΈ Remove the tag name from the section.
TagRename(old_name: str, new_name: str) β π Rename old_name to new_name.
TagRewrite(name: str, data: str) β βοΈ Change the tag value to data.
TagFile(file, [bytes: bool = False])
π Access debian control files (multiple RFC822 sections). Iterate to get TagSection objects, or use step() / jump().
close() β πͺ Close the file.jump(offset: int) -> bool β β© Jump to an offset.offset() -> int β π Current offset.step() -> bool β βοΈ Step forward.π Data descriptors:
section β π The current TagSection object.
TagSection(text: str, [bytes: bool = False])
π Access a single RFC822-style section. Readβonly dictionary with additional methods.
bytes() -> int β π Byte size of the section.find(name: str[, default=None]) -> str β π Return value for key.find_flag(name: str) -> int β β
Return 1 if value is yes/true, 0 otherwise.find_raw(name: str[, default=None]) -> str β π Return the complete 'key: value' line.keys() -> list β π List of all keys.write(file: int, order: List[str], rewrite: List[Tag]) -> None β βοΈ Rewrite the section to a file descriptor.π·οΈ Represent a package version. Supports comparison operators.
π Data descriptors:
arch β ποΈ Architecture of this version.depends_list β π Dict mapping dependency types to lists of lists of Dependency objects (orβgroups).depends_list_str β π Same but with (name, version, operator) tuples.downloadable β β
Whether the version can be downloaded.file_list β π List of (packagefile, index) tuples.hash β π’ Internal numeric hash.id β π’ Numeric ID.installed_size β πΎ Installed size.multi_arch β π Multiβarch state (compare with MULTI_ARCH_*).parent_pkg β π€ Parent Package.priority β π’ Priority integer (compare with PRI_*).priority_str β π·οΈ Priority as string.provides_list β π List of (providesname, providesver, version) tuples.section β π·οΈ Section.size β π Package file size.translated_description β π Description object (translated or untranslated).ver_str β π’ Version string.π·οΈ Multiβarch constants:
MULTI_ARCH_ALL = 1MULTI_ARCH_ALLOWED = 8MULTI_ARCH_ALL_ALLOWED = 9MULTI_ARCH_ALL_FOREIGN = 3MULTI_ARCH_FOREIGN = 2MULTI_ARCH_NO = 0MULTI_ARCH_NONE = 0MULTI_ARCH_SAME = 4
base64_encode(value: bytes) -> str
π Encode a bytestring to Base64. Input must not contain a null byte.
check_dep(pkg_ver: str, dep_op: str, dep_ver: str) -> bool
π Check that version pkg_ver matches dep_ver under operator dep_op (<,<=,=,>=,>). Example:
apt_pkg.check_dep('1', '
Generated by phpman v4.9.27 · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-07-18 16:13 @216.73.216.114
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
Enhanced by LLM: deepseek-v4-flash / taotoken.net / www.chedong.com - original format