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

监视增长的文件尾部是否存在某些关键字的有效方法是什么?


在外壳中,我可能会说:


tail -f "$file" | grep "$string" | while read hit; do

    #stuff

done


杨__羊羊
浏览 425回答 3
3回答

江户川乱折腾

def tail(f):    f.seek(0, 2)    while True:        line = f.readline()        if not line:            time.sleep(0.1)            continue        yield linedef 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”匹配。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python