Classes in apt_pkg

Todo

This should be split and cleaned up a bit.

Acquire

class Acquire
Run()
Fetch all the items which have been added by apt_pkg.GetPkgAcqFile().
Shutdown()
Shut the fetcher down.

PkgAcqFile

class PkgAcqFile
This class provides no methods or attributes

AcquireItem

class AcquireItem
ID
The ID of the item.
Complete
Is the item completely acquired?
Local
Is the item a local file?
IsTrusted
Can the file be trusted?
FileSize
The size of the file, in bytes.
ErrorText
The error message. For example, when a file does not exist on a http server, this will contain a 404 error message.
DestFile
The location the file is saved as.
DescURI
The source location.

Status:

Status
Integer, representing the status of the item.
StatIdle
Constant for comparing AcquireItem.Status.
StatFetching
Constant for comparing AcquireItem.Status
StatDone
Constant for comparing AcquireItem.Status
StatError
Constant for comparing AcquireItem.Status
StatAuthError
Constant for comparing AcquireItem.Status

ActionGroup

class ActionGroup

Normally, apt checkes the package cache after every modification for packages which are automatically installed but on which no package depends anymore (it collects the package garbage).

Using ActionGroups you can turn this off and therefore make your code much faster.

Initialize it using apt_pkg.GetPkgActionGroup(), eg:

apt_pkg.GetPkgActionGroup(depcache)
release()
Release the ActionGroup. This will reactive the collection of package garbage.

Configuration

class Configuration

The Configuration objects store the configuration of apt.

conf[key]
Return the value of the option given key key. If it does not exist, raise KeyError.
conf[key] = value
Set the option at key to value.
Find(key[, default=''])

Return the value for the given key key. This is the same as Configuration.get().

If key does not exist, return default.

FindFile(key[, default=''])

Return the filename hold by the configuration at key. This formats the filename correctly and supports the Dir:: stuff in the configuration.

If key does not exist, return default.

FindDir(key[, default='/'])

Return the absolute path to the directory specified in key. A trailing slash is appended.

If key does not exist, return default.

FindI(key[, default=0])

Return the integer value stored at key.

If key does not exist, return default.

FindB(key[, default=0])

Return the boolean value stored at key. This returns an integer, but it should be treated like True/False.

If key does not exist, return default.

Set(key, value)
Set the value of key to value.
Exists(key)
Check whether the key key exists in the configuration.
SubTree(key)
Return a sub tree starting at key. The resulting object can be used like this one.
List([key])

List all items at key. Normally, return the keys at the top level, eg. APT, Dir, etc.

Use key to specify a key of which the childs will be returned.

ValueList([key])
Same as Configuration.List(), but this time for the values.
MyTag()
Return the tag name of the current tree. Normally this is an empty string, but for subtrees it is the key of the subtree.
Clear(key)
Clear the configuration. Remove all values and keys at key.
keys([key])
Return all the keys, recursive. If key is specified, ... (FIXME)
has_key(key)
Return whether the configuration contains the key key.
get(key[, default=''])
This behaves just like dict.get() and Configuration.Find(), it returns the value of key or if it does not exist, default.

pkgCache

class pkgCache

The pkgCache class prov

cache[pkgname]
Return the Package() object for the package name given by pkgname.
Close()
Close the package cache.
Open([progress])
Open the package cache again. The parameter progress may be set to an apt.progress.OpProgress() object or None.
Update(progress, list[, pulseInterval])

Update the package cache.

The parameter progress points to an apt.progress.FetchProgress() object.

The parameter list refers to an object as returned by apt_pkg.GetPkgSourceList().

The optional parameter pulseInterval describes the interval between the calls to the FetchProgress.pulse() method.

DependsCount
The total number of dependencies.
PackageCount
The total number of packages available in the cache.
ProvidesCount
The number of provided packages.
VerFileCount

Todo

Seems to be some mixture of versions and pkgFile.

VersionCount
The total number of package versions available in the cache.
PackageFileCount
The total number of Packages files available (the Packages files listing the packages). This is the same as the length of the list in the attribute FileList.
FileList
A list of PackageFile objects.

PackageFile

class PackageFile

A PackageFile represents a Packages file, eg. /var/lib/dpkg/status.

Architecture
The architecture of the package file.
Archive
The archive (eg. unstable)
Component
The component (eg. main)
FileName
The name of the file.
ID
The ID of the package. This is an integer which can be used to store further information about the file [eg. as dictionary key].
IndexType
The sort of the index file. In normal cases, this is ‘Debian Package Index’.
Label
The Label, as set in the Release file
NotAutomatic
Whether packages from this list will be updated automatically. The default for eg. example is 0 (aka false).
NotSource

Whether the file has no source from which it can be updated. In such a case, the value is 1; else 0. /var/lib/dpkg/status is 0 for example.

Example:

for pkgfile in cache.FileList:
    if pkgfile.NotSource:
        print 'The file %s has no source.' % pkgfile.FileName
Origin
The Origin, as set in the Release file
Site
The hostname of the site.
Size
The size of the file.
Version
The version, as set in the release file (eg. “4.0” for “Etch”)

Example

#!/usr/bin/python
import apt_pkg


def main():
    """Example for PackageFile()"""
    apt_pkg.init()
    cache = apt_pkg.GetCache()
    for pkgfile in cache.FileList:
        print 'Package-File:', pkgfile.FileName
        print 'Index-Type:', pkgfile.IndexType # 'Debian Package Index'
        if pkgfile.NotSource:
            print 'Source: None'
        else:
            if pkgfile.Site:
                # There is a source, and a site, print the site
                print 'Source:', pkgfile.Site
            else:
                # It seems to be a local repository
                print 'Source: Local package file'
        if pkgfile.NotAutomatic:
            # The system won't be updated automatically (eg. experimental)
            print 'Automatic: No'
        else:
            print 'Automatic: Yes'
        print

if __name__ == '__main__':
    main()

Package

class Package

The pkgCache::Package objects are an interface to package specific features.

Attributes:

CurrentVer
The version currently installed, or None. This returns a Version object.
ID
The ID of the package. This can be used to store information about the package. The ID is an int value.
Name
This is the name of the package.
ProvidesList

A list of packages providing this package. More detailed, this is a list of tuples (str:pkgname, ????, Version).

If you want to check for check for virtual packages, the expression pkg.ProvidesList and not pkg.VersionList helps you. It detects if the package is provided by something else and is not available as a real package.

RevDependsList
An iterator of Dependency objects for dependencies on this package.
Section
The section of the package, as specified in the record. The list of possible sections is defined in the Policy.
VersionList
A list of Version objects for all versions available in the cache.

States:

SelectedState

The state we want it to be, ie. if you mark a package for installation, this is apt_pkg.SelStateInstall.

See Select states for a list of available states.

InstState

The state the currently installed version is in. This is normally apt_pkg.InstStateOK, unless the installation failed.

See Installed states for a list of available states.

CurState
The current state of the package (not installed, unpacked, installed, etc). See Package States for a list of available states.

Flags:

Auto
Whether the package was installed automatically as a dependency of another package. (or marked otherwise as automatically installed)
Essential
Whether the package is essential.
Important
Whether the package is important.

Example:

#!/usr/bin/python
"""Example for packages. Print all essential and important packages"""

import apt_pkg


def main():
    """Main."""
    apt_pkg.InitConfig()
    apt_pkg.InitSystem()
    cache = apt_pkg.GetCache()
    print "Essential packages:"
    for pkg in cache.Packages:
        if pkg.Essential:
            print " ", pkg.Name
    print "Important packages:"
    for pkg in cache.Packages:
        if pkg.Important:
            print " ", pkg.Name

if __name__ == "__main__":
    main()

Version

class Version

The version object contains all information related to a specific package version.

VerStr
The version, as a string.
Section
The usual sections (eg. admin, net, etc.). Prefixed with the component name for packages not in main (eg. non-free/admin).
Arch
The architecture of the package, eg. amd64 or all.
FileList
A list of (PackageFile, int: index) tuples for all Package files containing this version of the package.
DependsListStr

A dictionary of dependencies. The key specifies the type of the dependency (‘Depends’, ‘Recommends’, etc.).

The value is a list, containing items which refer to the or-groups of dependencies. Each of these or-groups is itself a list, containing tuples like (‘pkgname’, ‘version’, ‘relation’) for each or-choice.

An example return value for a package with a ‘Depends: python (>= 2.4)’ would be:

{'Depends': [
                [
                 ('python', '2.4', '>=')
                ]
            ]
}

The same for a dependency on A (>= 1) | B (>= 2):

{'Depends': [
                [
                    ('A', '1', '>='),
                    ('B', '2', '>='),
                ]
            ]
}
DependsList
This is basically the same as Version.DependsListStr, but instead of the (‘pkgname’, ‘version’, ‘relation’) tuples, it returns Dependency objects, which can assist you with useful functions.
ParentPkg
The Package object this version belongs to.
ProvidesList
This returns a list of all packages provided by this version. Like Package.ProvidesList, it returns a list of tuples of the form (‘virtualpkgname’, ???, Version), where as the last item is the same as the object itself.
Size
The size of the .deb file, in bytes.
InstalledSize
The size of the package (in kilobytes), when unpacked on the disk.
Hash
An integer hash value.
ID
An integer id.
Priority

The integer representation of the priority. This can be used to speed up comparisons a lot, compared to Version.PriorityStr.

The values are defined in the apt_pkg extension, see Priorities for more information.

PriorityStr
Return the priority of the package version, as a string, eg. “optional”.
Downloadable
Whether this package can be downloaded from a remote site.
TranslatedDescription
Return a Description object.

Dependency

class Dependency

Represent a dependency from one package to another one.

AllTargets()

A list of Version objects which satisfy the dependency, and do not conflict with already installed ones.

From my experience, if you use this method to select the target version, it is the best to select the last item unless any of the other candidates is already installed. This leads to results being very close to the normal package installation.

SmartTargetPkg()
Return a Version object of a package which satisfies the dependency and does not conflict with installed packages (the ‘natural target’).
TargetVer
The target version of the dependency, as string. Empty string if the dependency is not versioned.
TargetPkg
The Package object of the target package.
ParentVer
The Version object of the parent version, ie. the package which declares the dependency.
ParentPkg
The Package object of the package which declares the dependency. This is the same as using ParentVer.ParentPkg.
CompType
The type of comparison (>=, ==, >>, <=), as string.
DepType
The type of the dependency, as string, eg. “Depends”.
ID
The ID of the package, as integer.

Example: Find all missing dependencies

With the help of Dependency.AllTargets(), you can easily find all packages with broken dependencies:

#!/usr/bin/python
"""Check the archive for missing dependencies"""
import apt_pkg


def fmt_dep(dep):
    """Format a Dependency object [of apt_pkg] as a string."""
    ret = dep.TargetPkg.Name
    if dep.TargetVer:
        ret += " (%s %s)" % (dep.CompType, dep.TargetVer)
    return ret


def check_version(pkgver):
    """Check the version of the package"""
    missing = []

    for or_group in pkgver.DependsList.get("Pre-Depends", []) + \
                    pkgver.DependsList.get("Depends", []):
        if not any(dep.AllTargets() for dep in or_group):
            # If none of the or-choices can be satisfied, add it to missing
            missing.append(or_group)

    if missing:
        print "Package:", pkgver.ParentPkg.Name
        print "Version:", pkgver.VerStr
        print "Missing:",
        print ", ".join(" | ".join(fmt_dep(dep) for dep in or_group)
                        for or_group in missing)
        print


def main():
    """The main function."""
    apt_pkg.InitConfig()
    apt_pkg.InitSystem()

    cache = apt_pkg.GetCache()

    for pkg in sorted(cache.Packages, key=lambda pkg: pkg.Name):
        # pkg is from a list of packages, sorted by name.
        for version in pkg.VersionList:
            # Check every version
            for pfile, _ in version.FileList:
                if (pfile.Origin == "Debian" and pfile.Component == "main" and
                    pfile.Archive == "unstable"):
                    # We only want packages from Debian unstable main.
                    check_version(version)
                    break

if __name__ == "__main__":
    main()

Description

class Description

Represent the description of the package.

LanguageCode
The language code of the description
md5
The md5 hashsum of the description
FileList
A list of tuples (PackageFile, int: index).

pkgDepCache

class pkgDepCache

The pkgDepCache object contains various methods to manipulate the cache, to install packages, to remove them, and much more.

Commit(fprogress, iprogress)

Apply all the changes made.

The parameter fprogress has to be set to an instance of apt.progress.FetchProgress or one of its subclasses.

The parameter iprogress has to be set to an instance of apt.progress.InstallProgress or one of its subclasses.

FixBroken()
Try to fix all broken packages in the cache.
GetCandidateVer(pkg)

Return the candidate version of the package, ie. the version that would be installed normally.

The parameter pkg refers to an Package object, available using the pkgCache.

This method returns a Version object.

SetCandidateVer(pkg, version)
The opposite of pkgDepCache.GetCandidateVer(). Set the candidate version of the Package pkg to the Version version.
Upgrade([distUpgrade=False])

Perform an upgrade. More detailed, this marks all the upgradable packages for upgrade. You still need to call pkgDepCache.Commit() for the changes to apply.

To perform a dist-upgrade, the optional parameter distUpgrade has to be set to True.

FixBroken()
Fix broken packages.
ReadPinFile()
Read the policy, eg. /etc/apt/preferences.
MinimizeUpgrade()

Go over the entire set of packages and try to keep each package marked for upgrade. If a conflict is generated then the package is restored.

Todo

Explain better..

MarkKeep(pkg)
Mark the Package pkg for keep.
MarkDelete(pkg[, purge])
Mark the Package pkg for delete. If purge is True, the configuration files will be removed as well.
MarkInstall(pkg[, autoInst=True[, fromUser=True]])

Mark the Package pkg for install.

If autoInst is True, the dependencies of the package will be installed as well. This is the default.

If fromUser is True, the package will be marked as manually installed. This is the default.

SetReinstall(pkg)
Set if the Package pkg should be reinstalled.
IsUpgradable(pkg)

Return 1 if the package is upgradable.

The package can be upgraded by calling pkgDepCache.MarkInstall().

IsNowBroken(pkg)
Return 1 if the package is broken now (including changes made, but not committed).
IsInstBroken(pkg)
Return 1 if the package is broken on the current install. This takes changes which have not been committed not into effect.
IsGarbage(pkg)
Return 1 if the package is garbage, ie. if it is automatically installed and no longer referenced by other packages.
IsAutoInstalled(pkg)
Return 1 if the package is automatically installed (eg. as the dependency of another package).
MarkedInstall(pkg)
Return 1 if the package is marked for install.
MarkedUpgrade(pkg)
Return 1 if the package is marked for upgrade.
MarkedDelete(pkg)
Return 1 if the package is marked for delete.
MarkedKeep(pkg)
Return 1 if the package is marked for keep.
MarkedReinstall(pkg)
Return 1 if the package should be installed.
MarkedDowngrade(pkg)
Return 1 if the package should be downgraded.
KeepCount
Integer, number of packages marked as keep
InstCount
Integer, number of packages marked for installation.
DelCount
Number of packages which should be removed.
BrokenCount
Number of packages which are broken.
UsrSize
The size required for the changes on the filesystem. If you install packages, this is positive, if you remove them its negative.
DebSize
The size of the packages which are needed for the changes to be applied.

MetaIndex

Todo

Complete them

class MetaIndex
URI
Dist
IsTrusted
IndexFiles

PackageIndexFile

class PackageIndexFile
ArchiveURI(path)
Return the full url to path in the archive.
Label
Return the Label.
Exists
Return whether the file exists.
HasPackages
Return whether the file has packages.
Size
Size of the file
IsTrusted
Whether we can trust the file.

PkgManager

class PkgManager

Class, as returned by apt_pkg.GetPackageManager().

GetArchives(fetcher, list, records)

Add all the selected packages to the Acquire() object fetcher.

The parameter list refers to a PkgSourceList() object, as returned by apt_pkg.GetPkgSourceList().

The parameter records refers to a pkgRecords() object, as returned by apt_pkg.GetPkgRecords().

DoInstall()
Install the packages.
FixMissing()
Fix the installation if a package could not be downloaded.
ResultCompleted

A constant for checking whether the the result is ‘completed’.

Compare it against the return value of PkgManager.GetArchives() or PkgManager.DoInstall().

ResultFailed

A constant for checking whether the the result is ‘failed’.

Compare it against the return value of PkgManager.GetArchives() or PkgManager.DoInstall().

ResultIncomplete

A constant for checking whether the the result is ‘incomplete’.

Compare it against the return value of PkgManager.GetArchives() or PkgManager.DoInstall().

pkgRecords

class PkgRecords

Provide access to the packages records. This provides very useful attributes for fast (convient) access to some fields of the record.

See apt_pkg.GetPkgRecords() for initialization.

Lookup(verfile_iter)

Change the actual package to the package given by the verfile_iter.

The parameter verfile_iter refers to a tuple consisting of (PackageFile(), int: index), as returned by various attributes, including Version.FileList.

Example (shortened):

cand = depcache.GetCandidateVer(cache['python-apt'])
records.Lookup(cand.FileList[0])
# Now you can access the record
print records.SourcePkg # == python-apt
FileName
Return the field ‘Filename’ of the record. This is the path to the package, relative to the base path of the archive.
MD5Hash
Return the MD5 hashsum of the package This refers to the field ‘MD5Sum’ in the raw record.
SHA1Hash
Return the SHA1 hashsum of the package. This refers to the field ‘SHA1’ in the raw record.
SHA256Hash

Return the SHA256 hashsum of the package. This refers to the field ‘SHA256’ in the raw record.

New in version 0.7.9.

SourcePkg
Return the source package.
SourceVer
Return the source version.
Maintainer
Return the maintainer of the package.
ShortDesc
Return the short description. This is the summary on the first line of the ‘Description’ field.
LongDesc
Return the long description. These are lines 2-END from the ‘Description’ field.
Name
Return the name of the package. This is the ‘Package’ field.
Homepage
Return the Homepage. This is the ‘Homepage’ field.
Record

Return the whole record as a string. If you want to access fields of the record not available as an attribute, you can use apt_pkg.ParseSection() to parse the record and access the field name.

Example:

section = apt_pkg.ParseSection(records.Record)
print section['SHA256']

PkgSrcRecords

class PkgSrcRecords

This represents the entries in the Sources files, ie. the dsc files of the source packages.

Note

If the Lookup failed, because no package could be found, no error is raised. Instead, the attributes listed below are simply not existing anymore (same applies when no Lookup has been made, or when it has been restarted).

Lookup(pkgname)

Lookup the record for the package named pkgname. To access all available records, you need to call it multiple times.

Imagine a package P with two versions X, Y. The first Lookup(P) would set the record to version X and the second Lookup(P) to version Y.

Restart()

Restart the lookup.

Imagine a package P with two versions X, Y. The first Lookup(P) would set the record to version X and the second Lookup(P) to version Y.

If you now call Restart(), the internal position will be cleared. Now you can call Lookup(P) again to move to X.

Package
The name of the source package.
Version
A string describing the version of the source package.
Maintainer
A string describing the name of the maintainer.
Section
A string describing the section.
Record

The whole record, as a string. You can use apt_pkg.ParseSection() if you need to parse it.

You need to parse the record if you want to access fields not available via the attributes, eg. ‘Standards-Version’

Binaries
Return a list of strings describing the package names of the binaries created by the source package. This matches the ‘Binary’ field in the raw record.
Index
The index in the Sources files.
Files
The list of files. This returns a list of tuples with the contents (str: md5, int: size, str: path, str:type).
BuildDepends

Return the list of Build dependencies, as (str: package, str: version, int: op, int: type).

Values of op
Value Meaning
0x0 No Operation (no versioned build dependency)
0x10
(or) - this will be added to the other values
0x1 <= (less than or equal)
0x2 >= (greater than or equal)
0x3 << (less than)
0x4 >> (greater than)
0x5 == (equal)
0x6 != (not equal)
Values of type
Value Meaning
0 Build-Depends
1 Build-Depends-Indep
2 Build-Conflicts
3 Build-Conflicts-Indep

Example: In the following content, we will imagine a build-dependency:

Build-Depends: A (>= 1) | B (>= 1), C

This results in:

[('A', '1', 18, 0), # 18 = 16 + 2 = 0x10 + 0x2
 ('B', '1', 2, 0),
 ('C', '', 0, 0)]

This is not the same as returned by apt_pkg.ParseSrcDepends().

PkgSourceList

class PkgSourceList

This is for /etc/apt/sources.list.

FindIndex(pkgfile)
Return a PackageIndexFile object for the PackageFile pkgfile.
ReadMainList()
Read the main list.
GetIndexes(acq[, all])
Add the index files to the Acquire() object acq. If all is given and True, all files are fetched.

ProblemResolver

class ProblemResolver

The problem resolver helps when there are problems in the package selection. An example is a package which conflicts with another, already installed package.

Protect(pkg)

Protect the Package() object given by the parameter pkg.

Todo

Really document it.

InstallProtect()
Protect all installed packages from being removed.
Remove(pkg)

Remove the Package() object given by the parameter pkg.

Todo

Really document it.

Clear(pkg)

Reset the Package() pkg to the default state.

Todo

Really document it.

Resolve()
Try to resolve problems by installing and removing packages.
ResolveByKeep()
Try to resolve problems only by using keep.

TagFile

class TagFile

An object which represents a typical debian control file. Can be used for Packages, Sources, control, Release, etc.

Use apt_pkg.ParseTagFile() to parse a file.

Step()
Step forward to the next section. This simply returns 1 if OK, and 0 if there is no section
Offset()
Return the current offset (in bytes) from the beginning of the file.
Jump(offset)
Jump back/forward to offset. Use Jump(0) to jump to the beginning of the file again.
Section
This is the current TagSection() instance.

TagSection

class TagSection

Represent a single section of a debian control file.

section[key]
Return the value of the field at key. If key is not available, raise KeyError.
Bytes()
The number of bytes in the section.
Find(key, default='')
Return the value of the field at the key key if available, else return default.
FindFlag(key)
Find a yes/no value for the key key. An example for such a field is ‘Essential’.
get(key, default='')
Return the value of the field at the key key if available, else return default.
has_key(key)
Check whether the field with named by key exists.
keys()
Return a list of keys in the section.