#description下面这个小程序就像linux中命tail -f /var/log/messages一样,当运行时可以动态的显示文本文件里的信息哦!
import time import sys import os def tail(f): f.seek(0,2) #跳转到文本文件的最后的位置 while True: line = f.readline() if not line: time.sleep(0.1) continue yield line#匹配函数 def grep(lines,searchtext): for line in lines: if searchtext in line: yield line #协程 def print_match(matchtext): print(‘look for ‘,matchtext) while True: line = (yield)当执行完print语句后程序会停留在(yield)这里,直到有send(‘hello‘)语句过来时会触发程序继续运行哦! if matchtext in line: print (line) matches = [ print_match(‘python‘), print_match(‘love‘), print_match(‘test‘) ] for m in matches: m.__next__()#让 print(‘look for ‘,matchtext)这条语句执行完毕
www = tail(open(‘F:\code\mytest‘)) #往这个文件里写些内容吧,只要每一行中包括python,love,test,这三个词任意一个就会将哪一行输出
line = grep( www ,‘python‘) for lin in line: for m in matches: m.send(lin)很好玩哦!
时间: 2024-12-20 23:46:50