在Fabric中,如何检查是否存在Debian或Ubuntu软件包,如果不存在则安装它?

kle*_*ell 3 python ubuntu debian fabric

我需要这个来快速安装memcached作为Fabric脚本设置测试服务器的一部分.想我会在这里记录下来以备将来参考.

kle*_*ell 11

从这个超级用户评论和此stackoverflow答案拼凑而成.(注意:我正在运行root而不是使用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: https://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'):
        yes_install('memcached')
    with settings(warn_only=True):
        run('/etc/init.d/memcached restart', pty=False)
Run Code Online (Sandbox Code Playgroud)