第8章 迭代器
作业
1、自定义函数模拟range(1,7,2)
def myrange(start, stop, step=1):
while start < stop:
yield start
start += step
target = myrange(1,7,2)
print (target.__next__())
print (target.__next__())
print (next(target))
2、模拟管道,实现功能:tail -f access.log | grep '404'#模拟tail -f | grep
import time
def mytail(file):
with open(file,'rb') as f:
f.seek(0,2) #游标移到文件尾
while True:
line=f.readline()
if line:
yield line
else:
time.sleep(0.1)
def grep(pattern,lines):
for line in lines:
line=line.decode('utf-8')
print(line)
if pattern in line:
print ('查找到了')
yield line
for line in grep('404',mytail('access.log')):
print(line,end='')
#with open('access.log','a',encoding='utf-8') as f:
# f.write('出错啦404
')
# 或手工在access.log中添加包含404的新行,即会打印出结果

3、编写装饰器,实现初始化协程函数的功能
4、实现功能:grep -rl 'python' /etc
5、Python语言 实现八皇后问题