Python 调用 grep 失败

标签 python

我想在 Python 中执行这个命令

grep keyMessage logFile.log > keyMessageFile.log

这是我现在做的

from subprocess import call

keyMessage= 'keyMessage'
call(["grep", keyMessage,  "logFile.log"])

但我不知道如何添加 > keyMessageFile.log 部分

顺便说一句,我使用grep的原因是因为它比使用读取文件然后比较字符串然后写入文件要快得多

#更新 有我写的比较慢的python代码

keyMessage= 'keyMessage'

with open('logFile.log') as f:
    for line in f:
        with open(keyMessage+ '.txt', 'a') as newFile:
            if(keyMessage not in line):
                continue
            else:
                newFile.write(line)

最佳答案

最简单的方法(也相当安全)是:

from subprocess import check_call
from shlex import quote
check_call('grep %s logFile.log > keyMessageFile.log' % quote(keyMessage), shell=True)

但是,除非你真的需要 grep 的正则表达式匹配功能,并且你最终会在你的程序中读取 keyMessageFile.log,否则我认为以下内容不会慢得不合理:

def read_matching_lines(filename, key):
    with open(filename) as fp:
      for line in fp:
        if key in line:
          yield line

for matching_line in read_matching_lines('logFile.log', keyMessage):
    print(matching_line)

关于Python 调用 grep 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40781994/

相关文章:

python - 列组合计数,与顺序无关

Python使用简单脚本过度使用内存

python - 在pivot_table pandas之后丢失值

python - 适应不同雷电条件的OpenCV阈值

python - 如何在结构(python 部署工具)中的远程主机上创建新文件?

python - 具有多个 header 的 QStandardItemModel - 将 QTreeView header 与模型分离

python - 在 python 代码和 c++ 代码 (IPC) 之间共享信息

python - 在A列表中搜索一个元素的索引,如果没有找到,让用户知道

python - django 中的 Slug 字段错误

python - 在列表中搜索词典