用于在Linux PC上检索已安装软件的Python脚本

时间:2015-07-21 10:10:04

标签: python

是否有一种pythonic方法可以在Linux系统上检索软件安装的名称/版本?

或者Ubuntu,Fedora,CentOS等不同平台必须有不同的方法吗?

1 个答案:

答案 0 :(得分:0)

不,没有任何'pythonic'方法可以做到这一点。您仍然可以使用已安装的软件包管理器工具来搜索软件包。

我创建了代码来完成其中的一些操作。它目前仅支持dpkg(用于Debian和Ubuntu)和自制软件(用于Mac OS X),但很容易添加其他软件包管理器。

import re
import subprocess

PACKAGE_MANAGERS = {
    # "command": "test if package ? exists"-commnad
    "dpkg": "dpkg -s ?",
    "brew": "brew ls ?"
    # just add new package managers here
}

def find_package_manager():
    for pm in PACKAGE_MANAGERS.keys():
        if subprocess.call(["which", pm], stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0:
            return pm
    raise OSError("Unable to find package manager.")

def is_package_installed(name):
    return subprocess.call(PACKAGE_MANAGERS[find_package_manager()].replace("?", name)+" > /dev/null 2>&1", shell=True) == 0

def detect_package_version(name):
    if not is_package_installed(name):
        raise OSError("Unable to find package.")
    try:
        x = subprocess.check_output(name+" --version > /dev/null 2>&1", shell=True)
    except subprocess.CalledProcessError:
        pass
    else:
        a = re.findall("\\d+\\.\\d+\\.\\d+", x)
        if len(a) > 0:
            return a[0]
        b = re.findall("\\d+\\.\\d+", x)
        if len(b) > 0:
            return b[0]

print is_package_installed("python")
print detect_package_version("python")

对不起,这有点笨拙。

由于几乎所有程序都提供--version切换,我使用它来检测包版本。您可能希望使用包管理器的工具来完成它。