如何实现一个pythonic等效的tail -F? [英] How to implement a pythonic equivalent of tail -F?
本文介绍了如何实现一个pythonic等效的tail -F?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在shell中我可能会说:
tail -f$ file| grep$ string|同时读命中;做
#stuff
done
解决方案
嗯,最简单的方法是不断从文件中读取,检查新功能并测试命中。
import time
def watch(fn,words):
fp = open(fn,'r')
while True:
new = fp.readline()
#一旦所有的行被读取,这只是返回''
#,直到文件更改,并出现一个新行
如果新:
为单词中的单词:
如果在新的单词:
yield(word,new)
else:
time.sleep(0.5)
fn ='test.py'
word = ['word']
for hit_word,hit_sentence in watch(fn,words):
print找到%r in行:%r%(hit_word,hit_sentence)
如果您知道您的数据将以线条出现,此解决方案可以使用 readline
。
如果数据是某种流,则需要一个缓冲区,大于最大的字
为,并填写它。它的方式有点复杂...
What is the pythonic way of watching the tail end of a growing file for the occurrence of certain keywords?
In shell I might say:
tail -f "$file" | grep "$string" | while read hit; do
#stuff
done
解决方案
Well, the simplest way would be to constantly read from the file, check what's new and test for hits.
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)
This solution with readline
works if you know your data will appear in lines.
If the data is some sort of stream you need a buffer, larger than the largest word
you're looking for, and fill it first. It gets a bit more complicated that way...
这篇关于如何实现一个pythonic等效的tail -F?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文