Search code examples
pythonlinuxpackageaptdpkg

How do I programmatically get a list of packages from apt?


How can I use Python/python-apt to programmatically get the same result as "dpkg --get-selections"?


Solution

  • To display the first five packages:

    import apt_pkg
    
    apt_pkg.init()
    cache = apt_pkg.Cache()
    
    i = 5
    for pkg in cache.Packages:
      print(pkg)
      i -= 1
      if i < 0:
        break
    

    The output (when run on my Ubuntu system):

    $ python apt_package_list.py
    Reading package lists... Done
    Building dependency tree       
    Reading state information... Done
    <apt_pkg.Package object: name:'tesseract-ocr-epo' section: 'universe/graphics' id:48834>
    <apt_pkg.Package object: name:'omninotify' section: '' id:48674>
    <apt_pkg.Package object: name:'pipenightdreams' section: 'universe/games' id:43500>
    <apt_pkg.Package object: name:'mumudvb' section: 'universe/misc' id:41568>
    <apt_pkg.Package object: name:'mpg123-alsa' section: '' id:41448>
    <apt_pkg.Package object: name:'tbb-examples' section: 'universe/doc' id:38301>