協(xié)程和生成器很像但還是有些許的不同,主要的不同之處在于:
生成器是數(shù)據(jù)生產(chǎn)者
協(xié)程是數(shù)據(jù)消費者
首先再看一下生成器
def fib():
a, b = 0, 1
while True:
yield a
a, b = b, a+b
然后可以使用for循環(huán)遍歷
for i in fib():
print(i)
它是快速的,不會給內(nèi)存帶來很多壓力因為它會動態(tài)生成值而不是將它們存儲在列表中,現(xiàn)在,如果我們在上面的例子中使用yield,通常,就是一個協(xié)程。協(xié)程使用傳給它的值。一個基本的例子如下:
def grep(pattern):
print("Searching for", pattern)
while True:
line = (yield)
if pattern in line:
print(line)
可以看到,協(xié)程中yield語句的形式。它不包含任何初始值,而是由我們額外提供。我們可以使用send方法來提供值給它。下面是個簡單的例子:
def grep(pattern):
print("Searching for", pattern)
while True:
line = (yield)
if pattern in line:
print(line)
if __name__ == '__main__':
search = grep("cornator")
next(search) #output: ('Searching for', 'cornator')
search.send("I love px!")
search.send("I love px!")
search.send("I love px, cornator!") # output: I love px, cornator!
發(fā)送的值通過yield訪問。使用next()方法的原因是,運行協(xié)程需要使用它。就像生成器,協(xié)程不會自動運行。而是作為next()和.send()方法的響應(yīng)來運行它。因此,你需要運行next()來執(zhí)行到y(tǒng)ield表達式。
再看一例:
def averager():
total = 0.0
count = 0
average = None
while True:
term = yield average
total += term
count += 1
average = total/count
使用方法
>>> coro_avg = averager()
>>> next(coro_avg)
>>> coro_avg.send(10)
10.0
>>> coro_avg.send(30)
20.0
>>> coro_avg.send(5)
15.0
創(chuàng)建協(xié)程對象,調(diào)用 next 函數(shù),預激協(xié)程.由于我們在使用協(xié)程之前都必須激活協(xié)程,所以,我們通常可以寫一個裝飾器,專門用于預激協(xié)程:
from functools import wraps
def coroutine(func):
"""裝飾器:向前執(zhí)行到第一個`yield`表達式,預激`func`"""
@wraps(func)
def primer(*args,**kwargs):
gen = func(*args,**kwargs)
next(gen)
return gen
return primer
這樣我們就可以使用它了,使用方法如下:
from coroutil import coroutine #這里就是我們實現(xiàn)的裝飾器函數(shù)
@coroutine
def averager():
total = 0.0
count = 0
average = None
while True:
term = yield average
total += term
count += 1
average = total/count
我們再使用該函數(shù)的時候就不用調(diào)用next方法了,而是直接使用。
coro_avg = averager()
coro_avg.send(10)
coro_avg.send(30)
順便說一下yield from語法:
yield from x 表達式對x對象所做的第一件事就是調(diào)用iter(x),從中獲取迭代器,因此,x可以是任何可迭代的對象。yield from的主要功能是打開雙向通道,把最外面的調(diào)用方與最內(nèi)層的子生成器連接起來,這樣二者就可以直接發(fā)送和產(chǎn)出值,還可以直接傳入異常。而不是在位于中間的協(xié)程中添加大量的處理異常的樣板代碼。有了這個結(jié)構(gòu),協(xié)程可以通過以前不可能的方式委托職責。
yield from 幾大特征:
- 子生成器產(chǎn)出的值都直接傳給委派生成器的調(diào)用方(即客戶端代碼)。
- 使用 send() 方法發(fā)給委派生成器的值都直接傳給子生成器。如果發(fā)送的值是None,那么會調(diào)用子生成器的 next() 方法。如果發(fā)送的值不是 None,那么會調(diào)用子生成器的 send() 方法。如果調(diào)用的方法拋出StopIteration 異常,那么委派生成器恢復運行。任何其他異常都會向上冒泡,傳給委派生成器。
- 生成器退出時,生成器(或子生成器)中的 return expr 表達式會觸發(fā)StopIteration(expr) 異常拋出。
- yield from 表達式的值是子生成器終止時傳給 StopIteration 異常的第一個參數(shù)。
- 傳入委派生成器的異常,除了 GeneratorExit 之外都傳給子生成器的 throw() 方法。如果調(diào)用 throw() 方法時拋出 StopIteration 異常,委派生成器恢復運行。StopIteration 之外的異常會向上冒泡,傳給委派生成器。
- 如果把 GeneratorExit 異常傳入委派生成器,或者在委派生成器上調(diào)用 close() 方法,那么在子生成器上調(diào)用 close() 方法,如果它有的話。如果調(diào)用 close() 方法導致異常拋出,那么異常會向上冒泡,傳給委派生成器;否則,委派生成器拋出GeneratorExit 異常。
我們可以關(guān)閉協(xié)程通過調(diào)用.close()方法。
python3,中,協(xié)程可以使用asyncio模塊實現(xiàn),通過asnc def 聲明語句或者使用生成器。async def 類型協(xié)程是在python3.5中加入的,版本支持的情況下,建議使用它。基于生成器的協(xié)程應(yīng)該使用@asyncio.coroutine裝飾器,盡管這不是強制的。
import asyncio
@asyncio.coroutine
def test():
print("never scheduled")
async def hello_world():
print("Hello World!")
loop = asyncio.get_event_loop()
asyncio.ensure_future(test())
# Blocking call which returns when the hello_world() coroutine is done
loop.run_until_complete(hello_world())
loop.close()
調(diào)用一個協(xié)程不在代碼運行的時候開啟,調(diào)用返回的協(xié)程對象不在任何事情,直到你的調(diào)度器開始執(zhí)行。有兩種基本的方式開啟它的運行,調(diào)用await coroutine或者從其他coroutine中yield from coroutine,或者調(diào)度器執(zhí)行ensure_future()函數(shù)或者 AbstractEventLoop.create_task()方法。
協(xié)程運行只有當事件輪休運行的時候運行。
import asyncio
async def compute(x, y):
print("Compute %s + %s ..." % (x, y))
await asyncio.sleep(1.0)
return x + y
async def print_sum(x, y):
result = await compute(x, y)
print("%s + %s = %s" % (x, y, result))
loop = asyncio.get_event_loop()
loop.run_until_complete(print_sum(1, 2))
loop.close()
添加回調(diào)函數(shù)
import asyncio
async def slow_operation(future):
await asyncio.sleep(1)
future.set_result('Future is done!')
def got_result(future):
print(future.result())
loop.stop()
loop = asyncio.get_event_loop()
future = asyncio.Future()
asyncio.ensure_future(slow_operation(future))
future.add_done_callback(got_result)
try:
loop.run_forever()
finally:
loop.close()
最后看一例:
@asyncio.coroutine
def supervisor():
spinner = asyncio.async(spin('thinking!'))
print('spinner object:', spinner)
result = yield from slow_function()
spinner.cancel()
return result
這里能安全地取消協(xié)程的原因是按照定義,協(xié)程只能在暫停的yield處取消,因此可以處理CancelledError異常,執(zhí)行清除操作。