A curious Course on Coroutines and Concurrency-David Beazley(译)-1

1.生成器和协程的介绍
1.1
生成器是生成一系列的结果的函数

In [10]: def countdown(n):
....: while n > 0:
....: yield n
....: n -= 1
....:

In [11]: for i in countdown(5):
....: print(i)
....:
5
4
3
2
1
不同于返回一个value,生成器生成了一系列的value(使用yield语句)
现在可以暂时理解为循环

1.2
表现和普通函数很不一样
调用生成器的函数创造了生成器对象。然而它并不会立即执行。
In [20]: clear

In [21]: def countdown(n):
....: print("Count down from {}".format(n))
....: while n > 0:
....: yield n
....: n -= 1
....:

In [22]: x = countdown(10)

In [23]: x
Out[23]:

1.3生成器函数

In [47]: x.next()
Countdown from 10
Out[47]: 10
yield函数生成了一个值后会挂起该函数
函数在下一个next后继续

当整个生成器返回时,迭代停止

In [57]: x.next()

StopIteration Traceback (most recent call last)
in ()
----> 1 x.next()

实例1:(类似于unix中tail命令的实现)

import time
--def follow(thefiles):
--thefiles.seek(0,2)
--while True:
----line = thefiles.readline()
----if not line:
------time.sleep(1)
------continue
----yield line
.#可以查看webserver的日志文件
logfile = open("access-log.txt")
for line in follow(logfile):
--print(line,)

实例2:

生成器最强大的应用之一就是构建进程通信管道
(类似于unix的pipes shell命令)
思考:
你可以把多个多个生成器函数放到一个管道中,然后把信息用循环的方式放入管道
def grep(pattern,lines):
--for line in lines:
----if pattern in line:
------yield line
logfile = open("access-log")
loglines = follow(logfile)
pylines = grep("python",loglines)
for line in pylines:
--print(line,)

第一小节结束 随后会继续翻译

你可能感兴趣的:(A curious Course on Coroutines and Concurrency-David Beazley(译)-1)