# pydoc > apt_pkg

---
type: CommandReference
command: apt_pkg
mode: pydoc
section: 
source: pydoc3
---

## Quick Reference
- `apt_pkg.Cache()` — open the APT cache
- `apt_pkg.DepCache(cache)` — manage package states
- `apt_pkg.Package` — represent a package
- `apt_pkg.Version` — represent a package version
- `apt_pkg.config` — global APT configuration object
- `apt_pkg.SystemLock()` — context manager for locking the package system
- `apt_pkg.Acquire(progress)` — coordinate file retrieval
- `apt_pkg.PackageManager(depcache)` — install/remove packages
- `apt_pkg.get_architectures()` — list supported architectures
- `apt_pkg.version_compare(a, b)` — compare version strings

## Name
apt_pkg - Classes and functions wrapping the apt-pkg library.

## Synopsis
python
import apt_pkg
## Options (Classes and Functions)

### Classes

- `Acquire([progress])` — Coordinate retrieval of files via network or local file system. Key methods: `run()` returns `RESULT_CANCELLED`, `RESULT_CONTINUE`, `RESULT_FAILED`; `shutdown()`. Data descriptors: `fetch_needed`, `items`, `partial_present`, `total_needed`, `workers`. Constants: `RESULT_CANCELLED=2`, `RESULT_CONTINUE=0`, `RESULT_FAILED=1`.

- `AcquireFile(owner, uri, ...)` — Represent a file to be fetched. Inherits from `AcquireItem`. Key parameters: `destdir`, `destfile`, `hash`, `size`, `descr`, `short_descr`.

- `AcquireItem` — Represent a single item to be fetched. Not constructable directly. Data descriptors: `active_subprocess`, `complete`, `desc_uri`, `destfile`, `error_text`, `filesize`, `id`, `is_trusted`, `local`, `partialsize`, `status`. Status constants: `STAT_AUTH_ERROR=4`, `STAT_DONE=2`, `STAT_ERROR=3`, `STAT_FETCHING=1`, `STAT_IDLE=0`, `STAT_TRANSIENT_NETWORK_ERROR=5`.

- `AcquireItemDesc` — Provide description of an item and URI. Data descriptors: `description`, `owner`, `shortdesc`, `uri`.

- `AcquireWorker` — Represent a sub-process for fetching files. Data descriptors: `current_item`, `current_size`, `resumepoint`, `status`, `total_size`.

- `ActionGroup(depcache)` — Disable cleanup actions for batch modifications. Use with `with` statement. Methods: `release()`.

- `Cache([progress])` — In-core representation of APT's package list. Supports mapping from package name to `Package` object. Methods: `__getitem__`, `update(progress, sources, pulse_interval)`. Data descriptors: `depends_count`, `file_list`, `group_count`, `groups`, `is_multi_arch`, `package_count`, `packages`, `policy`, `provides_count`, `version_count`.

- `CacheMismatchError` — Exception raised when passing object from a different cache.

- `Cdrom()` — Identify Debian installation media and add to sources.list. Methods: `add(progress)`, `ident(progress)`.

- `Configuration()` — Represent APT configuration. Global object `apt_pkg.config`. Methods: `clear`, `dump`, `exists`, `find`, `find_b`, `find_dir`, `find_file`, `find_i`, `get`, `keys`, `list`, `my_tag`, `set`, `subtree`, `value_list`.

- `DepCache(cache)` — Extra information on package states. Key methods: `commit`, `fix_broken`, `get_candidate_ver`, `init`, `is_auto_installed`, `is_garbage`, `is_inst_broken`, `is_now_broken`, `is_upgradable`, `mark_auto`, `mark_delete`, `mark_install`, `mark_keep`, `marked_delete`, `marked_downgrade`, `marked_install`, `marked_keep`, `marked_reinstall`, `marked_upgrade`, `minimize_upgrade`, `read_pinfile`, `set_candidate_release`, `set_candidate_ver`, `set_reinstall`, `upgrade`. Data descriptors: `broken_count`, `deb_size`, `del_count`, `inst_count`, `keep_count`, `policy`, `usr_size`.

- `Dependency` — Represent a dependency from one package version to a package. Methods: `all_targets()`. Data descriptors: `comp_type`, `comp_type_deb`, `dep_type`, `dep_type_enum`, `dep_type_untranslated`, `id`, `parent_pkg`, `parent_ver`, `target_pkg`, `target_ver`. Type constants: `TYPE_CONFLICTS=5`, `TYPE_DEPENDS=1`, `TYPE_DPKG_BREAKS=8`, `TYPE_ENHANCES=9`, `TYPE_OBSOLETES=7`, `TYPE_PREDEPENDS=2`, `TYPE_RECOMMENDS=4`, `TYPE_REPLACES=6`, `TYPE_SUGGESTS=3`.

- `DependencyList` — List-like type for efficient access to multiple dependency objects.

- `Description` — Represent a package description. Data descriptors: `file_list`, `language_code`, `md5`.

- `Error` — Exception class for most python-apt exceptions. Inherits from `SystemError`.

- `FileLock(filename)` — Context manager for locking using a file. Use with `with` statement.

- `Group(cache, name)` — Group of packages with the same name. Methods: `find_package(architecture)`, `find_preferred_package()`.

- `GroupList` — Efficient representation of groups in `Cache`.

- `HashString(type, hash)` or `HashString('type:hash')` — Create a hash string. Methods: `verify_file(filename)`. Data descriptors: `hashtype`, `hashvalue`, `usable`.

- `HashStringList()` — Manage a list of `HashString` objects. Methods: `append`, `find`, `verify_file`. Data descriptors: `file_size`, `usable`.

- `Hashes([object])` — Calculate hashes for a file. Data descriptors: `hashes` (a `HashStringList`).

- `IndexFile` — Represent an index file. Methods: `archive_uri(path)`. Data descriptors: `describe`, `exists`, `has_packages`, `is_trusted`, `label`, `size`.

- `MetaIndex` — Information on meta-indexes (Release files). Data descriptors: `dist`, `index_files`, `is_trusted`, `uri`.

- `OrderList(depcache)` — Sequence type with ordering methods. Methods: `append`, `flag`, `is_flag`, `is_missing`, `is_now`, `order_configure`, `order_critical`, `order_unpack`, `score`, `wipe_flags`. Flags: `FLAG_ADDED=1`, `FLAG_ADD_PENDIG=2`, `FLAG_AFTER=256`, `FLAG_CONFIGURED=32`, `FLAG_IMMEDIATE=4`, `FLAG_IN_LIST=128`, `FLAG_LOOP=8`, `FLAG_REMOVED=64`, `FLAG_STATES_MASK=112`, `FLAG_UNPACKED=16`.

- `Package` — Represent a package. Methods: `get_fullname(pretty)`. Data descriptors: `architecture`, `current_state`, `current_ver`, `essential`, `has_provides`, `has_versions`, `id`, `important`, `inst_state`, `name`, `provides_list`, `rev_depends_list`, `selected_state`, `version_list`.

- `PackageFile` — An index file stored in cache. Data descriptors: `architecture`, `archive`, `codename`, `component`, `filename`, `id`, `index_type`, `label`, `not_automatic`, `not_source`, `origin`, `site`, `size`, `version`.

- `PackageList` — Efficient list of packages in `Cache`.

- `PackageManager(depcache)` — Fetch and install packages. Methods: `configure(pkg)`, `go(status_fd)`, `install(pkg, filename)`, `remove(pkg, purge)`, `reset()`, `do_install(status_fd)`, `fix_missing()`, `get_archives(fetcher, list, recs)`. Result constants: `RESULT_COMPLETED=0`, `RESULT_FAILED=1`, `RESULT_INCOMPLETE=2`.

- `PackageRecords(cache)` — Retrieve package information from records. Data descriptors: `filename`, `hashes`, `homepage`, `long_desc`, `maintainer`, `md5_hash`, `name`, `record`, `sha1_hash`, `sha256_hash`, `short_desc`, `source_pkg`, `source_ver`.

- `Policy(cache)` — Policy representation. Methods: `create_pin`, `get_candidate_ver`, `get_priority`, `init_defaults`, `read_pindir`, `read_pinfile`, `set_priority`.

- `ProblemResolver(depcache)` — Resolve dependency problems. Methods: `clear`, `protect`, `remove`, `resolve([fix_broken])`, `resolve_by_keep`.

- `SourceList()` — Represent sources.list. Methods: `find_index`, `get_indexes`, `read_main_list`. Data descriptors: `list` (list of `MetaIndex`).

- `SourceRecordFiles` — Look up source package records. Data descriptors: `hashes`, `path`, `size`, `type`.

- `SourceRecords()` — Look up source package records. Methods: `lookup(name)`, `restart()`, `step()`. Data descriptors: `binaries`, `build_depends`, `files`, `index`, `maintainer`, `package`, `record`, `section`, `version`.

- `SystemLock()` — Context manager for locking the package system. Use with `with` statement.

- `Tag` — Abstract base class for tag actions. Subclasses: `TagRemove`, `TagRename`, `TagRewrite`. Actions: `REMOVE=0`, `RENAME=1`, `REWRITE=2`.

- `TagFile(file, [bytes])` — Access to Debian control files. Iterator over `TagSection`. Methods: `close`, `jump`, `offset`, `step`. Data descriptors: `section`.

- `TagSection(text, [bytes])` — Access RFC822-style header sections. Methods: `bytes`, `find`, `find_flag`, `find_raw`, `get`, `keys`, `write`. Acts like a read-only dictionary.

- `Version` — Represent a package version. Methods: comparison operators. Data descriptors: `arch`, `depends_list`, `depends_list_str`, `downloadable`, `file_list`, `hash`, `id`, `installed_size`, `multi_arch`, `parent_pkg`, `priority`, `priority_str`, `provides_list`, `section`, `size`, `translated_description`, `ver_str`. Multi-arch constants: `MULTI_ARCH_ALL=1`, `MULTI_ARCH_ALLOWED=8`, `MULTI_ARCH_ALL_ALLOWED=9`, `MULTI_ARCH_ALL_FOREIGN=3`, `MULTI_ARCH_FOREIGN=2`, `MULTI_ARCH_NO=0`, `MULTI_ARCH_NONE=0`, `MULTI_ARCH_SAME=4`.

### Functions

- `base64_encode(value: bytes) -> str` — Encode bytes to Base64.
- `check_dep(pkg_ver, dep_op, dep_ver) -> bool` — Check if version comparison holds.
- `check_domain_list(host, domains) -> bool` — Check if host belongs to a comma-separated domain list.
- `dequote_string(string) -> str` — Decode HTTP percent-encoded characters.
- `get_architectures() -> list` — Return list of supported architectures.
- `get_lock(file, errors) -> int` — Create and lock a file; return fd or -1 on error.
- `gettext(msg, domain='python-apt') -> str` — Translate string (faster than Python's gettext).
- `init()` — Shorthand for `init_config()` and `init_system()`.
- `init_config()` — Load default configuration and config file.
- `init_system()` — Construct the apt_pkg system.
- `md5sum(object) -> str` — Return MD5 hash of a string or file.
- `open_maybe_clear_signed_file(file) -> int` — Open file, ignore PGP clear signature, return fd.
- `parse_commandline(config, options, argv) -> list` — Parse command line into configuration.
- `parse_depends(s, strip_multi_arch=True, architecture=None) -> list` — Parse dependency string into list of tuples.
- `parse_src_depends(s, strip_multi_arch=True, architecture=None) -> list` — Parse source dependency string.
- `pkgsystem_is_locked() -> bool` — Check if system is locked.
- `pkgsystem_lock() -> bool` — Acquire global lock.
- `pkgsystem_lock_inner() -> bool` — Reacquire dpkg lock.
- `pkgsystem_unlock() -> bool` — Release global lock.
- `pkgsystem_unlock_inner() -> bool` — Release dpkg lock.
- `quote_string(string, repl) -> str` — URL-encode a string.
- `read_config_dir(configuration, dirname)` — Read all config files in a directory.
- `read_config_file(configuration, filename)` — Read a config file.
- `read_config_file_isc(configuration, filename)` — Read a config file (ISC format).
- `sha1sum(object) -> str` — Return SHA1 hash.
- `sha256sum(object) -> str` — Return SHA256 hash.
- `sha512sum(object) -> str` — Return SHA512 hash.
- `size_to_str(bytes) -> str` — Human-readable size using SI prefixes.
- `str_to_time(rfc_time) -> int` — Convert RFC 1123 string to Unix timestamp.
- `string_to_bool(string) -> int` — Return 1, 0, or -1 for boolean strings.
- `time_rfc1123(unixtime) -> str` — Format Unix time as RFC 1123.
- `time_to_str(seconds) -> str` — Human-readable time (days, hours, minutes, seconds).
- `upstream_version(ver) -> str` — Extract upstream version.
- `uri_to_filename(uri) -> str` — Convert URI to safe filename.
- `version_compare(a, b) -> int` — Compare version strings.

### Data Constants

- `CURSTATE_*` — Package current state: `CONFIG_FILES=5`, `HALF_CONFIGURED=2`, `HALF_INSTALLED=4`, `INSTALLED=6`, `NOT_INSTALLED=0`, `UNPACKED=1`.
- `INSTSTATE_*` — Install state: `HOLD=2`, `HOLD_REINSTREQ=3`, `OK=0`, `REINSTREQ=1`.
- `PRI_*` — Priority: `EXTRA=5`, `IMPORTANT=2`, `OPTIONAL=4`, `REQUIRED=1`, `STANDARD=3`.
- `SELSTATE_*` — Selection state: `DEINSTALL=3`, `HOLD=2`, `INSTALL=1`, `PURGE=4`, `UNKNOWN=0`.
- `REWRITE_PACKAGE_ORDER` — List of fields for Package rewrite.
- `REWRITE_SOURCE_ORDER` — List of fields for Source rewrite.
- `config` — Global `Configuration` object.
- `VERSION = '2.4.14'`, `LIB_VERSION = '6.0.0'`.

## Examples

python
import apt_pkg

# Open cache
cache = apt_pkg.Cache()

# Get package
pkg = cache['apt']

# Use DepCache
depcache = apt_pkg.DepCache(cache)
depcache.mark_install(pkg)

# Use ActionGroup for batch operations
with apt_pkg.ActionGroup(depcache):
    depcache.mark_install(pkg)

# Lock system
with apt_pkg.SystemLock():
    # perform operations
    pass

# Compare versions
result = apt_pkg.version_compare('1.0', '2.0')  # negative
## See Also
- [apt_pkg documentation](https://apt-team.pages.debian.net/python-apt/library/apt_pkg.html)
- Debian Policy Manual: [Relationship fields](https://www.debian.org/doc/debian-policy/ch-relationships.html#s-depsyntax)