klenwell klenwell - 1 year ago 94
Python Question

In Fabric, how can I check if a Debian or Ubuntu package exists and install it if it does not?

I required this to quickly install memcached as part of a Fabric script setting up test servers. Figured I'd record it here for future reference.

Answer Source

Pieced this together from this superuser comment and this stackoverflow answer. (Note: I'm running as root rather than using sudo):

def package_installed(pkg_name):
    """ref: http:superuser.com/questions/427318/#comment490784_427339"""
    cmd_f = 'dpkg-query -l "%s" | grep -q ^.i'
    cmd = cmd_f % (pkg_name)
    with settings(warn_only=True):
        result = run(cmd)
    return result.succeeded

def yes_install(pkg_name):
    """ref: http://stackoverflow.com/a/10439058/1093087"""
    run('apt-get --force-yes --yes install %s' % (pkg_name))

def make_sure_memcached_is_installed_and_running():
    if not package_installed('memcached'):
    with settings(warn_only=True):
        run('/etc/init.d/memcached restart', pty=False)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download