gpt4 book ai didi

.json Loggly 文件的 Python 编程

转载 作者:行者123 更新时间:2023-12-01 05:21:46 27 4
gpt4 key购买 nike

我想搜索长 .json loggly 文件中的特定字符串,包括其行号,并且还想打印搜索行上方和下方的 5 行。你能帮我吗?

它总是返回“NOT FOUND”。之后,现在我只能通过下面显示的程序获得一些输出。将 open('logg.json', 'r') 作为 f: 对于 ln,enumerate(f) 中的行: 如果“错误崩溃日志”在行: 我=ln-25 对于 (ln-25,ln+25) 中的 i: l = linecache.getline('logg.json', i) 我+=1 打印(ln,l) print("下一个错误")

最佳答案

file.readlines() 返回行列表。 Lines 确实包含换行符 (\n)。

您需要指定换行符来匹配行:

ln = data.index("error CRASHLOG\n")

如果你想找到包含目标字符串的行,你需要迭代这些行:

with open('logg.json', 'r') as f:
for ln, line in enumerate(f):
if "error CRASHLOG" in line:
# You now know the line index (`ln`)
# Print above/below 5 lines here.
break
else:
print("Not Found")

顺便说一句,这种工作可以使用 grep(1) 轻松完成:

grep -C 5 'error CRASHLOG' logg.json || echo 'Not Found'

更新

以下是更完整的代码:

from collections import deque
from itertools import islice, chain
import sys

with open('logg.json', 'r') as f:
last_lines = deque(maxlen=5) # contains the last (up to) 5 lines.
for ln, line in enumerate(f):
if "error CRASHLOG" in line:
sys.stdout.writelines(chain(last_lines, [line], islice(f, 5)))
last_lines.append(line)
else:
print("Not Found")

关于.json Loggly 文件的 Python 编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22166414/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com