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

发布于 2021-01-29 15:23:38

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

在外壳中,我可能会说:

tail -f "$file" | grep "$string" | while read hit; do
    #stuff
done
关注者
0
被浏览
45
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    好吧,最简单的方法是不断读取文件,检查新内容并测试命中率。

    import time
    
    def watch(fn, words):
        fp = open(fn, 'r')
        while True:
            new = fp.readline()
            # Once all lines are read this just returns ''
            # until the file changes and a new line appears
    
            if new:
                for word in words:
                    if word in new:
                        yield (word, new)
            else:
                time.sleep(0.5)
    
    fn = 'test.py'
    words = ['word']
    for hit_word, hit_sentence in watch(fn, words):
        print "Found %r in line: %r" % (hit_word, hit_sentence)
    

    readline如果您知道数据将成行显示,则此解决方案有效。

    如果数据是某种类型的流,则需要一个缓冲区,该缓冲区大于word要查找的最大缓冲区,然后首先填充它。这样变得有点复杂…



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看