标签:执行函数 opened fir 概念 += 函数名 coding ide port
一、概念
#题目一: def my_range(start,stop,step=1): while start < stop: yield start start+=step #执行函数得到生成器,本质就是迭代器 obj=my_range(1,7,2) #1 3 5 print(next(obj)) print(next(obj)) print(next(obj)) print(next(obj)) #StopIteration #应用于for循环 for i in my_range(1,7,2): print(i)
import time def tail(filepath): with open(filepath,‘rb‘) as f: f.seek(0,2) while True: line=f.readline() if line: yield line else: time.sleep(0.2) def grep(pattern,lines): for line in lines: line=line.decode(‘utf-8‘) if pattern in line: yield line for line in grep(‘404‘,tail(‘access.log‘)): print(line,end=‘‘) #测试 with open(‘access.log‘,‘a‘,encoding=‘utf-8‘) as f: f.write(‘出错啦404\n‘)
二、yield与return的区别
标签:执行函数 opened fir 概念 += 函数名 coding ide port
原文地址:https://www.cnblogs.com/datatool/p/13508522.html