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.
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.
A Cache object represents the cache used by APT which contains information about packages. The object itself provides no means to modify the cache or the installed packages, see the classes DepCache and PackageManager for such functionality.
The constructor takes an optional argument which must be a subclass of apt.progress.base.OpProgress. This object will then be used to display information during the cache opening process (or possible creation of the cache).
Update the index files used by the cache. A call to this method does not affect the current Cache object, instead a new one should be created in order to use the changed index files.
The parameter progress takes an apt.progress.base.AcquireProgress object which will display the progress of fetching the index files. The parameter sources takes a SourceList object which lists the sources. The parameter progress takes an integer describing the interval (in microseconds) in which the pulse() method of the progress object will be called.
A sequence of Package objects, implemented as a PackageList object.
A simple sequence-like object which only provides a length and an implementation of __getitem__ for accessing packages at a certain index. Apart from being iterable, it can be used in the following ways:
A DepCache object provides access to more information about the objects made available by the Cache object as well as means to mark packages for removal and installation, among other actions.
The constructor takes a single argument which specifies the Cache object the new object shall be related to. While it is theoretically possible to create multiple DepCache objects for the same cache, they will not be independent from each other since they all access the same underlying C++ object.
Objects of this type provide several methods. Most of those methods are safe to use and should never raise any exception (all those methods for requesting state information or marking changes). If a method is expected to raise an exception, it will be stated in the description.
Commit all marked changes, while reporting the progress of fetching packages via the apt.progress.base.AcquireProgress object given by acquire_progress and reporting the installation of the package using the apt.progress.base.InstallProgress object given by install_progress.
If this fails, an exception of the type SystemError will be raised.
Mark the packages for upgrade under the same conditions apt-get does. If dist_upgrade is True, also allow packages to be upgraded if they require installation/removal of other packages; just like apt-get dist-upgrade.
Despite returning a boolean value, this raises SystemError and does not return False if an error occurred.
The following methods can mark a single package for installation, removal, etc:
The following methods can be used to check the state of a package:
DepCache objects also provide several attributes containing information on the marked changes:
Abstraction of a package manager. This object takes care of retrieving packages, ordering the installation, and calling the package manager to do the actual installation.
Add all packages marked for installation (or upgrade, anything which needs a download) to the Acquire object referenced by fetcher.
The parameter list specifies a SourceList object which is used to retrieve the information about the archive URI for the packages which will be fetched.
The parameter records takes a PackageRecords object which will be used to look up the file name of the package.
Create a new ActionGroup() object for the DepCache object given by the parameter depcache.
ActionGroup() objects make operations on the cache faster by delaying certain cleanup operations until the action group is released.
An action group is also a context manager and therefore supports the with statement. But because it becomes active as soon as it is created, you should not create an ActionGroup() object before entering the with statement. Thus, you should always use the following form:
with apt_pkg.ActionGroup(depcache):
...
For code which has to run on Python versions prior to 2.5, you can also use the traditional way:
actiongroup = apt_pkg.ActionGroup(depcache)
...
actiongroup.release()
In addition to the methods required to implement the context manager interface, ActionGroup objects provide the following method:
ProblemResolver objects take care of resolving problems with dependencies. They mark packages for installation/removal and try to satisfy all dependencies. The constructor takes a single argument of the type apt_pkg.DepCache to determine the cache that shall be manipulated in order to resolve the problems.
Represent a package. A package is uniquely identified by its name and each package can have zero or more versions which can be accessed via the version_list property. Packages can be installed and removed by a DepCache object.
Attributes:
A boolean value determining whether the list available via the attribute provides_list has at least one element. This value may be used in combination with has_versions to check whether a package is virtual; that is, it has no versions and is provided at least once:
pkg.has_provides and not pkg.has_versions
A boolean value determining whether the list available via the attribute version_list has at least one element. This value may be used in combination with has_provides to check whether a package is virtual; that is, it has no versions and is provided at least once:
pkg.has_provides and not pkg.has_versions
An iterator of Dependency objects for dependencies on this package. The returned iterator is implemented by the class DependencyList:
A simple list-like type for representing multiple dependency objects in an efficient manner; without having to generate all Dependency objects in advance.
States:
The state we want it to be, ie. if you mark a package for installation, this is apt_pkg.SELSTATE_INSTALL.
See Package selection states for a list of available states.
The state the currently installed version is in. This is normally apt_pkg.INSTSTATE_OK, unless the installation failed.
See Installed states for a list of available states.
Flags:
#!/usr/bin/python
"""Example for packages. Print all essential and important packages"""
import apt_pkg
def main():
"""Main."""
apt_pkg.init_config()
apt_pkg.init_system()
cache = apt_pkg.Cache()
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()
The version object contains all information related to a specific package version.
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', '>='),
]
]
}
The comparison operators are not the Debian ones, but the standard comparison operators as used in languages such as C and Python. This means that ‘>’ means “larger than” and ‘<’ means “less than”.
The integer representation of the priority. This can be used to speed up comparisons a lot, compared to priority_str.
The values are defined in the apt_pkg extension, see Priorities for more information.
Represent a dependency from one package to another one.
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.
The following constants describe all values the attribute dep_type_enum can take:
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.target_pkg.name
if dep.target_ver:
ret += " (%s %s)" % (dep.comp_type, dep.target_ver)
return ret
def check_version(pkgver):
"""Check the version of the package"""
missing = []
for or_group in pkgver.depends_list.get("Pre-Depends", []) + \
pkgver.depends_list.get("Depends", []):
if not any(dep.all_targets() 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.parent_pkg.name
print "Version:", pkgver.ver_str
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.init_config()
apt_pkg.init_system()
cache = apt_pkg.Cache()
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.version_list:
# Check every version
for pfile, _ in version.file_list:
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()
Representation of the policy of the Cache object given by cache. This provides a superset of policy-related functionality compared to the DepCache class. The DepCache can be used for most purposes, but there may be some cases where a special policy class is needed.
Represent a Release file as stored in the cache.
- uri¶
- The URI the meta index file is located at, as a string.
- dist¶
- The distribution stored in the meta index, as a string.
- is_trusted¶
- A boolean value determining whether the meta index can be trusted. This is True for signed Release files.
Represent an index file, that is, package indexes, translation indexes, and source indexes.
Provide access to an index file stored in the cache, such as /var/lib/dpkg/status.
Whether the file has no source from which it can be updated. In such a case, the value is True; else False. For example, it is False for /var/lib/dpkg/status.
Example:
for pkgfile in cache.file_list:
if pkgfile.not_source:
print 'The file %s has no source.' % pkgfile.filename
The following example shows how to use PackageFile:
#!/usr/bin/python
import apt_pkg
def main():
"""Example for PackageFile()"""
apt_pkg.init()
cache = apt_pkg.Cache()
for pkgfile in cache.file_list:
print 'Package-File:', pkgfile.filename
print 'Index-Type:', pkgfile.index_type # 'Debian Package Index'
if pkgfile.not_source:
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.not_automatic:
# The system won't be updated automatically (eg. experimental)
print 'Automatic: No'
else:
print 'Automatic: Yes'
print
if __name__ == '__main__':
main()
Represent a Release file and provide means to read information from the file. This class provides several methods:
Provide further information about the packages in the Cache object cache. This efficiently parses the package files to provide information not available in the cache, such as maintainer, hash sums, description, and the file name of the package. It also provides the complete record of the package.
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 file_list attributes such as Version.file_list.
Example (shortened):
cand = depcache.GetCandidateVer(cache['python-apt'])
records.Lookup(cand.FileList[0])
# Now you can access the record
print records.SourcePkg # == python-apt
Return the SHA256 hashsum of the package. This refers to the field ‘SHA256’ in the raw record.
New in version 0.7.9.
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.TagSection to parse the record and access the field name.
Example:
section = apt_pkg.TagSection(records.record)
print section['SHA256'] # Use records.sha256_hash instead
Provide an easy way to look up the records of source packages and provide easy attributes for some widely used fields of the record.
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).
Look up the source package with the given name. Each call moves the position of the records parser forward. If there are no more records, return None. If the lookup failed this way, access to any of the attributes will result in an AttributeError.
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. A third call would return None and access to any of the below attributes will result in an AttributeError
Restart the lookup process. This moves the parser to the first package and lookups can now be made just like on a new object.
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.
The Acquire Interface is responsible for all sorts of downloading in apt. All packages, index files, etc. downloading is done using the Acquire functionality.
The apt_pkg module provides a subset of this functionality which allows you to implement file downloading in your applications. Together with the PackageManager class you can also fetch all the packages marked for installation.
Coordinate the retrieval of files via network or local file system (using copy://path/to/file style URIs). Items can be added to an Acquire object using various means such as creating instances of AcquireFile or the methods SourceList.get_indexes() and PackageManager.get_archives().
Acquire objects maintain a list of items which will be fetched or have been fetched already during the lifetime of this object. To add new items to this list, you can create new AcquireFile objects which allow you to add single files.
The constructor takes an optional parameter progress which takes an apt.progress.base.AcquireProgress object. This object may then report progress information (see apt.progress.text for reporting progress to a I/O stream and apt.progress.gtk2 for GTK+ progress reporting).
Acquire items have two methods to start and stop the fetching:
Shut the fetcher down. This removes all items from the queue and makes all AcquireItem, AcquireWorker, AcquireItemDesc objects useless. Accessing an object of one of those types can cause a segfault then.
Removing an item does not mean that the already fetched data will be removed from the destination. Instead, APT might use the partial result and continue from thereon.
Furthermore, they provide three attributes which provide information on how much data is already available and how much data still needs to be fetched:
They also provide two attributes representing the items being processed and the workers fetching them:
The Acquire class comes with three constants which represents the results of the run() method:
An AcquireItem object represents a single item of an Acquire object. It is an abstract class to represent various types of items which are implemented as subclasses. The only exported subclass is AcquireFile which can be used to fetch files.
Status:
The following attribute represents the status of the item. This class provides several constants for comparing against this value which are listed here as well.
Create a new AcquireFile() object and register it with acquire, so it will be fetched. You must always keep around a reference to the object, otherwise it will be removed from the Acquire queue again.
The parameter owner 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 description of the download. It may be used to describe the item in the progress class. short_descr is the short form of it.
The parameters descr and short_descr can be used to specify descriptions for the item. The string passed to descr should describe the file and its origin (e.g. “http://localhost sid/main python-apt 0.7.94.2”) and the string passed to short_descr should be one word such as the name of a package.
Normally, the file will be stored in the current directory using the file name given in the URI. This directory can be changed by passing the name of a directory to the destdir parameter. It is also possible to set a path to a file using the destfile parameter, but both can not be specified together.
In terms of attributes, this class is a subclass of AcquireItem and thus inherits all its attributes.
An AcquireWorker object represents a sub-process responsible for fetching files from remote locations. There is no possibility to create instances of this class from within Python, but a list of objects of currently active workers is provided by Acquire.workers.
Objects of this type provide several attributes which give information about the worker’s current activity.
An AcquireItemDesc object stores information about the item which can be used to describe the item. Objects of this class are used in the progress classes, see the apt.progress.base.AcquireProgress documentation for information how.
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.
The module provides the two classes Hashes and HashString for generic hash support:
Calculate all supported hashes of the object. object may either be a string, in which cases the hashes of the string are calculated; or a file() object or file descriptor, in which case the hashes of its contents is calculated. The calculated hashes are then available via attributes:
HashString objects store the type of a hash and the corresponding hash. They are used by e.g IndexRecords.lookup(). The first parameter, type refers to one of “MD5Sum”, “SHA1” and “SHA256”. The second parameter hash is the corresponding hash.
You can also use a combined form by passing a string with type and hash separated by a colon as the only argument. For example:
HashString("MD5Sum:d41d8cd98f00b204e9800998ecf8427e")
The apt_pkg module also provides the functions md5sum(), sha1sum() and sha256sum() for creating a single hash from a bytes or file 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.7.100: Added support for using file descriptors.
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.7.100: Added support for using file descriptors.
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.7.100: Added support for using file descriptors.
Debian control files are files containing multiple stanzas of RFC 822-style header sections. They are widely used in the Debian community, and can represent many kinds of information. One example for such a file is the /var/lib/dpkg/status file which contains a list of the currently installed packages.
The apt_pkg module provides two classes to read those files and parts thereof and provides a function RewriteSection() which takes a TagSection() object and sorting information and outputs a sorted section as a string.
An object which represents a typical debian control file. Can be used for Packages, Sources, control, Release, etc. Such an object provides two kinds of API which should not be used together:
The first API implements the iterator protocol and should be used whenever possible because it has less side effects than the other one. It may be used e.g. with a for loop:
tagf = apt_pkg.TagFile(open('/var/lib/dpkg/status'))
for section in tagfile:
print section['Package']
Changed in version 0.7.100: Added support for using gzip files, via gzip.GzipFile or any file containing a compressed gzip stream.
A TagFile is its own iterator. This method is part of the iterator protocol and returns a TagSection object for the next section in the file. If there is no further section, this method raises the StopIteration exception.
From Python 3 on, this method is not available anymore, and the global function next() replaces it.
The second API uses a shared TagSection object which is exposed through the section attribute. This object is modified by calls to step() and jump(). This API provides more control and may use less memory, but is not recommended because it works by modifying one object. It can be used like this:
tagf = apt_pkg.TagFile(open('/var/lib/dpkg/status'))
tagf.step()
print tagf.section['Package']
Represent a single section of a debian control file.
Return True if section has a key key, else False.
New in version 0.7.100.
Rewrite the section given by section using rewrite_list, and order the fields according to order.
The parameter order is a list object containing the names of the fields in the order they should appear in the rewritten section. apt_pkg.REWRITE_PACKAGE_ORDER and apt_pkg.REWRITE_SOURCE_ORDER are two predefined lists for rewriting package and source sections, respectively.
The parameter rewrite_list is a list of tuples of the form (tag, newvalue[, renamed_to]), where tag describes the field which should be changed, newvalue the value which should be inserted or None to delete the field, and the optional renamed_to can be used to rename the field.
Check that the given requirement is fulfilled; that is, that the version string given by pkg_ver matches the version string dep_ver under the condition specified by the operator ‘dep_op’ (<,<=,=,>=,>).
Return True if pkg_ver matches dep_ver under the condition ‘dep_op’; for example:
>>> apt_pkg.check_dep("1.0", ">=", "1")
True
The following two functions provide the ability to parse dependencies. They use the same format as Version.depends_list_str.
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.parse_depends("PkgA (>= VerA) | PkgB (>= VerB)")
[[('PkgA', 'VerA', '>='), ('PkgB', 'VerB', '>=')]]
Note that multiarch dependency information is stripped off by default. You can force the full dependency info (including the multiarch info) by passing “False” as a additional parameter to this function.
Note
The behavior of this function is different than the behavior of the old function ParseDepends(), because the third field operation uses > instead of >> and < instead of << which is specified in control files.
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.parse_depends("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.parse_src_depends("a (>= 01) [i386 amd64]")
[[('a', '01', '>=')]]
Note
The behavior of this function is different than the behavior of the old function ParseDepends(), because the third field operation uses > instead of >> and < instead of << which is specified in control files.
Provide access to and manipulation of APT’s configuration which is used by many classes and functions in this module to define their behavior. There are options to install recommends, change the root directory and much more. For an (incomplete) list of available options, see the apt.conf(5) manual page.
The most important Configuration object is the one available by the module’s apt_pkg.config attribute. It stores the global configuration which affects the behavior of most functions and is initialized by a call to the function init_config(). While possible, it is generally not needed to create other instances of this class.
For accessing and manipulating the configuration space, objects of this type provide an interface which resembles Python mapping types like dict.
In addition, they provide methods to resemble the interface provided by the C++ class and some more mapping methods which have been enhanced to support some more advanced configuration features:
Return a string containing the values in the configuration object, in the standard apt.conf(5) format.
New in version 0.7.100.
Locate the given key using find() and return the path to the file/directory. This uses a special algorithms which moves upwards in the configuration space and prepends the values of the options to the result. These methods are generally used for the options stored in the ‘Dir’ section of the configuration.
As an example of how this works, take a look at the following options and their values:
Option | Value |
---|---|
Dir | / |
Dir::Etc | etc/apt/ |
Dir::Etc::main | apt.conf |
A call to find_file() would now return /etc/apt/apt.conf because it prepends the values of “Dir::Etc” and “Dir” to the value of “Dir::Etc::main”:
>>> apt_pkg.config.find_file("Dir::Etc::main")
'/etc/apt/apt.conf'
If the special configuration variable “RootDir” is set, this value would be prepended to every return value, even if the path is already absolute. If not, the function ends as soon as an absolute path is created (once an option with a value starting with “/” is read).
The method find_dir() does exactly the same thing as find_file(), but adds a trailing forward slash before returning the value.
Return a new apt_pkg.Configuration object which starts at the given option. Example:
apttree = config.subtree('APT')
apttree['Install-Suggests'] = config['APT::Install-Suggests']
The configuration space is shared with the main object which means that all modifications in one object appear in the other one as well.
Parse the command line in argv into the configuration space. The list options contains a list of 3-tuples or 4-tuples in the form:
(short_option: str, long_option: str, variable: str[, type: str])
The element short_option is one character, the long_option element is the name of the long option, the element variable the name of the configuration option the result will be stored in and type is one of ‘HasArg’, ‘IntLevel’, ‘Boolean’, ‘InvBoolean’, ‘ConfigFile’, ‘ArbItem’. The default type is ‘Boolean’.
Type | What happens if the option is given |
---|---|
HasArg | The argument given to the option is stored in the target. |
IntLevel | The integer value in the target is increased by one |
Boolean | The target variable is set to True. |
InvBoolean | The target variable is set to False. |
ConfigFile | The file given as an argument to this option is read in and all configuration options are added to the configuration object (APT’s ‘-c’ option). |
ArbItem | The option takes an argument key*=*value, and the configuration option at key is set to the value value (APT’s ‘-o’ option). |
When working on the global cache, it is important to lock the cache so other programs do not modify it. This module provides two context managers for locking the package system or file-based locking.
Context manager for locking the package system. The lock is established as soon as the method __enter__() is called. It is released when __exit__() is called. If the lock can not be acquired or can not be released an exception is raised.
This should be used via the ‘with’ statement. For example:
with apt_pkg.SystemLock():
... # Do your stuff here.
... # Now it's unlocked again
Once the block is left, the lock is released automatically. The object can be used multiple times:
lock = apt_pkg.SystemLock()
with lock:
...
with lock:
...
Context manager for locking using a file. The lock is established as soon as the method __enter__() is called. It is released when __exit__() is called. If the lock can not be acquired or can not be released, an exception is raised.
This should be used via the ‘with’ statement. For example:
with apt_pkg.FileLock(filename):
...
Once the block is left, the lock is released automatically. The object can be used multiple times:
lock = apt_pkg.FileLock(filename)
with lock:
...
with lock:
...
For Python versions prior to 2.5, similar functionality is provided by the following three functions:
Create an empty file at the path specified by the parameter filename and lock it. If this fails and errors is True, the function raises an error. If errors is False, the function returns -1.
The lock can be acquired multiple times within the same process, and can be released by calling os.close() on the return value which is the file descriptor of the created file.
A Cdrom object identifies Debian installation media and adds them to /etc/apt/sources.list. The C++ version of this class is used by the apt-cdrom tool and using this class, you can re-implement apt-cdrom in Python, see Writing your own apt-cdrom.
The class apt.cdrom.Cdrom is a subclass of this class and provides some additional functionality for higher level use and some shortcuts for setting some related configuration options.
This class provides two functions which take an instance of apt.progress.base.CdromProgress as their argument.
Represent the list of sources stored in files such as /etc/apt/sources.list.
Encode the given bytes string (which may not contain a null byte) using base64, for example, on Python 3 and newer:
>>> apt_pkg.base64_encode(b"A")
'QQ=='
on Python versions prior to 3, the ‘b’ before the string has to be omitted.
See if the host name given by host is one of the domains given in the comma-separated list list or a subdomain of one of them.
>>> apt_pkg.check_domain_list("alioth.debian.org","debian.net,debian.org")
True
Dequote the string specified by the parameter string, e.g.:
>>> apt_pkg.dequote_string("%61%70%74%20is%20cool")
'apt is cool'
Escape the string string, replacing any character not allowed in a URL or specified by repl with its ASCII value preceded by a percent sign (so for example ‘ ‘ becomes ‘%20’).
>>> apt_pkg.quote_string("apt is cool","apt")
'%61%70%74%20is%20cool'
Return a string describing the size in a human-readable manner using SI prefix and base-10 units, e.g. ‘1k’ for 1000, ‘1M’ for 1000000, etc.
Example:
>>> apt_pkg.size_to_str(10000)
'10.0k'
Parse the string input and return one of -1, 0, 1.
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.string_to_bool("yes")
1
>>> apt_pkg.string_to_bool("no")
0
>>> apt_pkg.string_to_bool("not-recognized")
-1
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.str_to_time('Thu, 01 Jan 1970 00:00:00 GMT')
0
Format the unix time specified by the integer seconds, according to the requirements of RFC 1123.
Example:
>>> apt_pkg.time_rfc1123(0)
'Thu, 01 Jan 1970 00:00:00 GMT'
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.time_to_str(3601)
'1h0min1s'
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.uri_to_filename('http://debian.org/index.html')
'debian.org_index.html'
Compare two versions, a and b, and return an integer value which has the same meaning as the built-in cmp() function’s return value has, see the following table for details.
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. |