为了账号安全,请及时绑定邮箱和手机立即绑定

如何实现tail -F的pythonic等效项?

如何实现tail -F的pythonic等效项?

杨__羊羊 2019-12-27 10:21:02
监视增长的文件尾部是否存在某些关键字的有效方法是什么?在外壳中,我可能会说:tail -f "$file" | grep "$string" | while read hit; do    #stuffdone
查看完整描述

3 回答

?
江户川乱折腾

TA贡献1851条经验 获得超5个赞

def tail(f):

    f.seek(0, 2)


    while True:

        line = f.readline()


        if not line:

            time.sleep(0.1)

            continue


        yield line


def process_matches(matchtext):

    while True:

        line = (yield)  

        if matchtext in line:

            do_something_useful() # email alert, etc.



list_of_matches = ['ERROR', 'CRITICAL']

matches = [process_matches(string_match) for string_match in list_of_matches]    


for m in matches: # prime matches

    m.next()


while True:

    auditlog = tail( open(log_file_to_monitor) )

    for line in auditlog:

        for m in matches:

            m.send(line)

我用它来监视日志文件。在完整的实现中,我将list_of_matches保留在配置文件中,以便可以用于多种用途。在我的增强功能列表中,是对正则表达式的支持,而不是简单的“ in”匹配。


查看完整回答
反对 回复 2019-12-27
  • 3 回答
  • 0 关注
  • 422 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信