apt_pkg — The low-level bindings for apt-pkg

The apt_pkg extensions provides a more low-level way to work with apt. It can do everything apt can, and is written in C++. It has been in python-apt since the beginning.

Module Initialization

Initialization is needed for most functions, but not for all of them. Some can be called without having run init*(), but will not return the expected value.

apt_pkg.initConfig()
Initialize the configuration of apt. This is needed for most operations.
apt_pkg.initSystem()
Initialize the system.
apt_pkg.init()
Deprecated function. Use initConfig() and initSystem() instead.

Object initialization

apt_pkg.GetCache([progress])
Return a pkgCache object. The optional parameter progress specifies an instance of apt.progress.OpProgress() which will display the open progress.
apt_pkg.GetCdrom()

Return a Cdrom object with the following methods:

Cdrom.Ident(progress)
Identify the cdrom. The parameter progress refers to an apt.progress.CdromProgress() object.
Cdrom.Add(progress)
Add the cdrom to the sources.list file. The parameter progress refers to an apt.progress.CdromProgress() object.
apt_pkg.GetDepCache(cache)
Return a pkgDepCache object. The parameter cache specifies an instance of pkgCache (see GetCache()).
apt_pkg.GetPkgSourceList()
Return a PkgSourceList object.
apt_pkg.GetPackageManager(depcache)
Return a new PkgManager object. The parameter depcache specifies a pkgDepCache object as returned by GetDepCache().
apt_pkg.GetPkgActionGroup(depcache)
Return a new ActionGroup object. The parameter depcache specifies a pkgDepCache object as returned by GetDepCache().
apt_pkg.GetPkgProblemResolver(depcache)
Return a new ProblemResolver object. The parameter depcache specifies a pkgDepCache object as returned by GetDepCache().
apt_pkg.GetPkgRecords(cache)

Return a new PkgRecords object.

The parameter cache refers to an pkgCache object, as returned by GetCache().

apt_pkg.GetPkgSrcRecords()
Return a new PkgSrcRecords object.

The Acquire interface

apt_pkg.GetAcquire([progress])

Return an Acquire object. This is a class which allows you to fetch files, or archive contents. The parameter progress refers to an apt.progress.FetchProgress() object.

Acquire items have multiple methods:

Acquire.Run()
Fetch all the items which have been added by GetPkgAcqFile().
Acquire.Shutdown()
Shut the fetcher down.
Acquire.TotalNeeded
The total amount of bytes needed (including those of files which are already present)
Acquire.FetchNeeded
The total amount of bytes which need to be fetched.
Acquire.PartialPresent
Whether some files have been acquired already. (???)
apt_pkg.GetPkgAcqFile(aquire, uri[, md5, size, descr, shortDescr, destDir, destFile])

Create a new PkgAcqFile() object and register it with acquire, so it will be fetched.

The parameter acquire refers to an Acquire() object as returned by GetAcquire(). The file will be added to the Acquire queue automatically.

The parameter uri refers to the location of the file, any protocol of apt is supported.

The parameter md5 refers to the md5sum of the file. This can be used for checking the file.

The parameter size can be used to specify the size of the package, which can then be used to calculate the progress and validate the download.

The parameter descr is a descripition of the download. It may be used to describe the item in the progress class. shortDescr is the short form of it.

You can use destDir to manipulate the directory where the file will be saved in. Instead of destDir, you can also specify the full path to the file using the parameter destFile. You can not combine both.

Hash functions

The apt_pkg module also provides several hash functions. If you develop applications with python-apt it is often easier to use these functions instead of the ones provides in Python’s hashlib module.

apt_pkg.md5sum(object)

Return the md5sum of the object. object may either be a string, in which case the md5sum of the string is returned, or a file() object (or a file descriptor), in which case the md5sum of its contents is returned.

Changed in version 0.8.0: Added support for using file descriptors.

apt_pkg.sha1sum(object)

Return the sha1sum of the object. object may either be a string, in which case the sha1sum of the string is returned, or a file() object (or a file descriptor), in which case the sha1sum of its contents is returned.

Changed in version 0.8.0: Added support for using file descriptors.

apt_pkg.sha256sum(object)

Return the sha256sum of the object. object may either be a string, in which case the sha256sum of the string is returned, or a file() object (or a file descriptor), in which case the sha256sum of its contents is returned.

Changed in version 0.8.0: Added support for using file descriptors.

Debian control files

apt_pkg.ParseSection(text)
Parse the string given in the parameter text and return a TagSection object.
apt_pkg.ParseTagFile(file)

Parse the given file and return a TagFile() object. file may be a file() object, a file descriptor, or anything providing a fileno() method.

Changed in version 0.8.0: Added support for using file descriptors.

apt_pkg.RewriteSection(section, order, rewrite_list)

RewriteSection(Section,Order,RewriteList) -> String

The section rewriter allows a section to be taken in, have fields added, removed or changed and then put back out. During this process the fields within the section are sorted to corrispond to a proper order. Order is a list of field names with their proper capitialization. apt_pkg.RewritePackageOrder and apt_pkg.RewriteSourceOrder are two predefined orders. RewriteList is a list of tuples. Each tuple is of the form:

(Tag,NewValue[,RenamedTo])

Tag specifies the tag in the source section. NewValue is the new value of that tag and the optional RenamedTo field can cause the tag to be changed. If NewValue is None then the tag is removed Ex. (‘Source’,’apt’,’Package’) is used for .dsc files.

apt_pkg.RewritePackageOrder
The order in which the information for binary packages should be rewritten, i.e. the order in which the fields should appear.
apt_pkg.RewriteSourceOrder
The order in which the information for source packages should be rewritten, i.e. the order in which the fields should appear.

Dependencies

apt_pkg.CheckDep(pkgver, op, depver)

Check that the dependency requirements consisting of op and depver can be satisfied by the version pkgver.

Example:

>>> bool(apt_pkg.CheckDep("1.0", ">=", "1"))
True
apt_pkg.ParseDepends(depends)

Parse the string depends which contains dependency information as specified in Debian Policy, Section 7.1.

Returns a list. The members of this list are lists themselves and contain one or more tuples in the format (package,version,operation) for every ‘or’-option given, e.g.:

>>> apt_pkg.ParseDepends("PkgA (>= VerA) | PkgB (>= VerB)")
[[('PkgA', 'VerA', '>='), ('PkgB', 'VerB', '>=')]]
apt_pkg.ParseSrcDepends(depends)

Parse the string depends which contains dependency information as specified in Debian Policy, Section 7.1.

Returns a list. The members of this list are lists themselves and contain one or more tuples in the format (package,version,operation) for every ‘or’-option given, e.g.:

>>> apt_pkg.ParseDepends("PkgA (>= VerA) | PkgB (>= VerB)")
[[('PkgA', 'VerA', '>='), ('PkgB', 'VerB', '>=')]]

Furthemore, this function also supports to limit the architectures, as used in e.g. Build-Depends:

>>> apt_pkg.ParseSrcDepends("a (>= 01) [i386 amd64]")
[[('a', '01', '>=')]]

Configuration

apt_pkg.Config
A Configuration()-like object with the default configuration. This is implemented in the ConfigurationPtr class, which has the same API like the Configuration class.
apt_pkg.newConfiguration()
Return a new Configuration object.
apt_pkg.ReadConfigFile(configuration, filename)
Read the configuration file specified by the parameter filename and add the settings therein to the Configuration() object specified by the parameter configuration
apt_pkg.ReadConfigDir(configuration, dirname)
Read configuration files in the directory specified by the parameter dirname and add the settings therein to the Configuration() object specified by the parameter configuration.
apt_pkg.ReadConfigFileISC(configuration, filename)
Read the configuration file specified by the parameter filename and add the settings therein to the Configuration() object specified by the parameter configuration
apt_pkg.ParseCommandLine(configuration, options, argv)

This function is like getopt except it manipulates a configuration space. output is a list of non-option arguments (filenames, etc). options is a list of tuples of the form (‘c’,”long-opt or None”, ”Configuration::Variable”,”optional type”).

Where type may be one of HasArg, IntLevel, Boolean, InvBoolean, ConfigFile, or ArbItem. The default is Boolean.

Locking

apt_pkg.GetLock(filename)

Create an empty file at the path specified by the parameter filename and lock it.

While the file is locked by a process, calling this function in another process returns -1.

When the lock is not required anymore, the file descriptor should be closed using os.close().

apt_pkg.PkgSystemLock()
Lock the global pkgsystem.
apt_pkg.PkgSystemUnLock()
Unlock the global pkgsystem.

Other functions

apt_pkg.Base64Encode(string)

Encode the given string using base64, e.g:

>>> apt_pkg.Base64Encode(u"A")
'QQ=='
apt_pkg.CheckDomainList(host, list)

See if Host is in a ‘,’ seperated list, e.g.:

apt_pkg.CheckDomainList("alioth.debian.org","debian.net,debian.org")
apt_pkg.DeQuoteString(string)

Dequote the string specified by the parameter string, e.g.:

>>> apt_pkg.DeQuoteString("%61%70%74%20is%20cool")
'apt is cool'
apt_pkg.QuoteString(string, repl)

For every character listed in the string repl, replace all occurences in the string string with the correct HTTP encoded value:

>>> apt_pkg.QuoteString("apt is cool","apt")
'%61%70%74%20is%20cool'
apt_pkg.SizeToStr(size)

Return a string presenting the human-readable version of the integer size. When calculating the units (k,M,G,etc.) the size is divided by the factor 1000.

Example:

>>> apt_pkg.SizeToStr(10000)
'10.0k'
apt_pkg.StringToBool(input)

Parse the string input and return one of -1, 0, 1.

Return values
Value Meaning
-1 The string input is not recognized.
0 The string input evaluates to False.
+1 The string input evaluates to True.

Example:

>>> apt_pkg.StringToBool("yes")
1
>>> apt_pkg.StringToBool("no")
0
>>> apt_pkg.StringToBool("not-recognized")
-1
apt_pkg.StrToTime(rfc_time)

Convert the RFC 1123 conforming string rfc_time to the unix time, and return the integer. This is the opposite of TimeRFC1123().

Example:

>> apt_pkg.StrToTime('Thu, 01 Jan 1970 00:00:00 GMT')
0
apt_pkg.TimeRFC1123(seconds)

Format the unix time specified by the integer seconds, according to the requirements of RFC 1123.

Example:

>>> apt_pkg.TimeRFC1123(0)
'Thu, 01 Jan 1970 00:00:00 GMT'
apt_pkg.TimeToStr(seconds)

Format a given duration in a human-readable manner. The parameter seconds refers to a number of seconds, given as an integer. The return value is a string with a unit like ‘s’ for seconds.

Example:

>>> apt_pkg.TimeToStr(3601)
'1h0min1s'
apt_pkg.UpstreamVersion(version)
Return the string version, eliminating everything following the last ‘-‘. Thus, this should be equivalent to version.rsplit('-', 1)[0].
apt_pkg.URItoFileName(uri)

Take a string uri as parameter and return a filename which can be used to store the file, based on the URI.

Example:

>>> apt_pkg.URItoFileName('http://debian.org/index.html')
'debian.org_index.html'
apt_pkg.VersionCompare(a, b)

Compare two versions, a and b, and return an integer value which has the same characteristic as the built-in cmp() function.

Return values
Value Meaning
> 0 The version a is greater than version b.
= 0 Both versions are equal.
< 0 The version a is less than version b.

Package States

apt_pkg.CurStateConfigFiles
apt_pkg.CurStateHalfConfigured
apt_pkg.CurStateHalfInstalled
apt_pkg.CurStateInstalled
apt_pkg.CurStateNotInstalled
apt_pkg.CurStateUnPacked

Dependency types

apt_pkg.DepConflicts
apt_pkg.DepDepends
apt_pkg.DepObsoletes
apt_pkg.DepPreDepends
apt_pkg.DepRecommends
apt_pkg.DepReplaces
apt_pkg.DepSuggests

Installed states

apt_pkg.InstStateHold
apt_pkg.InstStateHoldReInstReq
apt_pkg.InstStateOk
apt_pkg.InstStateReInstReq

Priorities

apt_pkg.PriExtra
apt_pkg.PriImportant
apt_pkg.PriOptional
apt_pkg.PriRequired
apt_pkg.PriStandard

Select states

apt_pkg.SelStateDeInstall
apt_pkg.SelStateHold
apt_pkg.SelStateInstall
apt_pkg.SelStatePurge
apt_pkg.SelStateUnknown

Build information

apt_pkg.Date
The date on which this extension has been compiled.
apt_pkg.LibVersion
The version of the apt_pkg library. This is not the version of apt, nor the version of python-apt.
apt_pkg.Time
The time this extension has been built.
apt_pkg.Version
The version of apt (not of python-apt).