有没有更好的方法使用python代码从输出中提取数据

use*_*922 1 python

我正在编写一个新手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]
Run Code Online (Sandbox Code Playgroud)

分裂和看起来我将不得不应用更多的分裂来获得所需的数据.git和1.7.9.5(版本名称).

我只想弄清楚是否有更好的方法来实现这一目标.

请指教..

谢谢,-Vijay

eca*_*mur 6

正如您所观察到的那样,尝试解析人类可读的输出是脆弱的.幸运的是,你可以将其替换dpkg -ldpkg-query -W -f='${Package}\t${Version}\n'被设计到生产机器可读的输出.有关选项的完整列表,请参见http://manpages.ubuntu.com/manpages/lucid/man1/dpkg-query.1.htmldpkg-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
Run Code Online (Sandbox Code Playgroud)