python - 从文本文档中获取第 n 列(Python 3)

标签 python linux bash python-3.x

我正在尝试编写代码,允许 Linux Mint 用户为他们机器上已安装的任何软件安装所有推荐的软件包。要获取已安装的软件包列表,我在 bash 中运行以下命令:

grep 'install' /var/log/dpkg.log

这会返回如下内容:

2015-09-24 19:39:01 install libportsmf0:amd64 <none> 0.1~svn20101010-4
2015-09-24 19:39:02 install libsbsms10:amd64 <none> 2.0.2-1
2015-09-24 19:39:03 install libsoxr0:amd64 <none> 0.1.1-1
2015-09-24 19:39:04 install libwxbase3.0-0:amd64 <none> 3.0.2-1+b1
2015-09-24 19:39:05 install libwxgtk3.0-0:amd64 <none> 3.0.2-1+b1
2015-09-24 19:39:07 install libvamp-hostsdk3:amd64 <none> 1:2.5-dmo6
2015-09-24 19:39:08 install audacity-data:all <none> 2.0.6-2
2015-09-24 19:39:10 install audacity:amd64 <none> 2.0.6-2
2015-09-25 11:47:36 install hardinfo:amd64 <none> 0.5.1-1.4
2015-09-25 12:14:35 install libstdc++6:i386 <none> 4.9.2-10
2015-09-25 12:14:36 install libudev1:i386 <none> 215+12+betsy
2015-09-25 12:14:37 install libtinfo5:i386 <none> 5.9+20140913-1+b1
2015-09-25 12:14:38 install libbsd0:i386 <none> 0.7.0-2
2015-09-25 12:14:39 install libedit2:i386 <none> 3.1-20140620-2
2015-09-25 12:14:40 install nvidia-installer-cleanup:amd64 <none> 20141201+1

我需要的是能够抓取每一行的第四列,其中显示包名称。所以 libportsmf0:amd64, libsbsms10:amd64... 到目前为止,我已经尝试将 grep 'install' 的输出通过管道传输到一个文件,使用 Python 3 打开该文件,并使用 for 循环获取第三列,这样

import os
def recommends():
    os.system("grep 'install' /var/log/dpkg.log >> ~/irFiles.txt")

file1 = '~/irFiles.txt'

但我还没有弄清楚如何设置 for 循环。 谢谢!

最佳答案

为什么不直接通过 bash 来做呢?

使用cut

# something like that
$ cat /var/log/dpkg.log | grep 'install' | cut -f4 -d" "

字段参数-f<number>可以不同,我有status中间,对我来说是-f5 . -d参数表示它由空格而不是制表符分隔。

通过 grep -v 排除不需要的输出

如果您想排除类似 <none> 的内容在输出中,您可以像这样使用反向 grep (grep -v) 扩展命令:

# something like that
$ cat /var/log/dpkg.log | grep 'install' | cut -f4 -d" " | grep -v '<none>'

很容易管道更多grep -v整个命令后的命令可以排除更多(也可以用一个正则表达式来完成,但这种方式更容易理解)。

使用 sort 删除末尾的重复项和 uniq

如果输出中有重复项,您也可以使用 sort 删除它们和 uniq .

# something like that
$ cat /var/log/dpkg.log | grep 'install' | cut -f4 -d" " | grep -v '<none>' | sort | uniq

python

如果你真的想用 Python 来做,你可以这样做:

# the with statement is not really necessary, but recommended.
with open("/var/log/dpkg.log") as logfile:
    for line in logfile:
        # covers also 'installed', 'half-installed', …
        # for deeper processing you can use re module, but it's very likely not necessary
        if "install" in line.split()[3]:  # or [4]
            # your code here
            print(line)

关于python - 从文本文档中获取第 n 列(Python 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32855559/

相关文章:

linux - 项目错误 : Unknown module(s) in QT: webkitwidgets

c++ - 在不附加 GDB 的情况下获取所有线程的堆栈跟踪

c - 是否可以像 C 一样在 shell bash 函数中将变量定义为静态变量?

linux - 无法删除超过三天的目录

git - 运行 git pull 遍历所有子目录

python - 在Python中,将一天中的特定时间与纪元中的当前时间进行比较

python 3 : using "all" on class variables

python - django.core.exceptions.ImproperlyConfigured : Field name `id` is not valid for model

python - 不同版本 Python 的条件 shebang 行

linux - Redis和ElasticSearch能否存在于同一台服务器上