读取日志文件,搜索关键字,打印关键字前5行。yield、deque实例

from collections import deque

def search(lines, pattern, history=5):
previous_lines = deque(maxlen=history)
for line in lines:
if pattern in line:
yield line,previous_lines
previous_lines.append(line)

if __name__ == '__main__':
with open('log.txt','r',encoding='utf-8') as f:
for line, prevlines in search(f, 'return', 1):
for pline in prevlines:
print(pline,end='')
print(line,end='')
print ('-'*20)
posted @ 2016-05-02 23:31  电神  阅读(548)  评论(0编辑  收藏  举报