我正在编写一个新手 python 代码来查找我将从中运行代码的系统上安装的软件列表。如果没有安装该软件,我打算告诉用户。
输出将是这样的:(dpkg -l)
A snippet below:
----------------
ii git 1:1.7.9.5-1 fast, scalable, distributed revision control system
ii git-man 1:1.7.9.5-1 fast, scalable, distributed revision control system (manual pages)
c = subprocess.Popen(['dpkg','-l'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
list_of_packages,error = c.communicate()
for item in list_of_packages.split('\n'):
print item.split('ii')[-1]
哪个拆分看起来我将不得不应用更多的拆分来获取所需的数据。 git 和 1.7.9.5(版本名称)。
我只是想弄清楚是否有更好的方法来实现这一目标。
请指教..
谢谢, -维杰
请您参考如下方法:
正如您所观察到的,尝试解析人类可读的输出是脆弱的。幸运的是,您可以将 dpkg -l 替换为 dpkg-query -W -f='${Package}\t${Version}\n' ,它旨在生成机器可读的输出。参见 http://manpages.ubuntu.com/manpages/lucid/man1/dpkg-query.1.html dpkg-query 选项的完整列表。
>>> args = ["dpkg-query", "-W", "-f=${Package}\t${Version}\n"]
>>> out, err = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
>>> print out #output is summarized, clearly
git 1:1.7.9.5-1
git-man 1:1.7.9.5-1
