使用yield语句,可以让函数生成一个结果序列,而不仅仅是一个值
#!/usr/bin/env python3 def countdown(n): print("Counting down", end = " ") while n > 0: yield n n -= 1 c = countdown(5) for i in range(4): print(c.__next__()) #c.next() in python2下面的第一个例子创建了一个简单的处理管道,类似于
tail -f |grep python 语句
#!/usr/bin/env python3 import time 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 wwwlog = tail(open("access-log")) pylines = grep(wwwlog, "python") for line in pylines: print(line, end=" ")函数可以编写成一个任务程序,用来处理发送给他的一系列输入,这类函数被称之为协程。它是通过将yield语句作为表达式(yield)的形式创建的。调用协程函数的next()函数,协程函数将向前执行到第一条(yield)语句。使用协程函数的seed()为协程发送某个值之前,协程会暂时中止。发送值之后,协程中的(yield)表达式将返回这个值,而接下来的语句会处理它。调用协程函数的close()语句将结束协程函数的调用。
下面是一个日志查找程序:
#!/usr/bin/env python3 import time def tail(f): f.seek(0,2) while True: line = f.readline() if not line: time.sleep(0.1) continue yield line def print_matches(matchtext): print("Looking for %s" %(matchtext)) while True: line = (yield) if matchtext in line: print(line) matchers = [ print_matches("python"), print_matches("guido"), print_matches("jpython") ] for m in matchers: m.next() wwwlog = tail(open("access-log")) for line in wwwlog: for m in matchers: m.seed(line)
