List or search all installed apps on Ubuntu 18.04 with Python.

I was bored… Of course this can be done easily in the terminal, but what’s the fun in that? This should work on any flavor of Debian/Ubuntu.

import os
import subprocess as sp
'''
Pipe to file in terminal:

$ flatpak list --app --show-details > ~/Documents/installed-flatpack.log
$ dpkg --get-selections > ~/Documents/installed-software.log

Not using Debian? Here's some others, including BSD Unix.
$ rpm -qa
$ yum list installed
$ pacman -Qi
$ pkg_version | less

Why Python when you have pipes, greps, and such?
Why not?
'''

def get_flatpak():
    cmd=['/usr/bin/flatpak','list','--app','--show-details']
    process=sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE)
    stdout, stderr = process.communicate()
    return stdout.decode().replace('\t',' ').split('\n')

def get_apt():
    cmd=['/usr/bin/dpkg','--get-selections']
    process=sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE)
    stdout, stderr = process.communicate()
    return stdout.decode().replace('\t',' ').split('\n')
    
if __name__=="__main__":
    
    names_only = []
    flatpak = True
    apt = True
    search_string='gimp'
    
    if flatpak:
        pkgs = get_flatpak()
        for pkg in pkgs:
            if ' ' in pkg:
                names_only.append(pkg.split()[0])
                
    if apt:
        pkgs = get_apt()
        for pkg in pkgs:
            if ' ' in pkg:
                names_only.append(pkg.split()[0])
        
    for app in names_only:
        if search_string:
            if search_string not in app.lower():
                continue
        print(app)