1. 程式人生 > >python闖關_Day008

python闖關_Day008

第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\n')
# 或手工在access.log中新增包含404的新行,即會打印出結果

  

 

3、編寫裝飾器,實現初始化協程函式的功能
4、實現功能:grep -rl 'python' /etc
5、Python語言 實現八皇后問題