python yield用法舉例說明

1  yield基本用法

典型的例子html

  斐波那契(Fibonacci)數列是一個很是簡單的遞歸數列,除第一個和第二個數外,任意一個數均可由前兩個數相加獲得。1 2 3 5 8……python

def fab(max): 
    n, a, b = 0, 0, 1 
    while n < max: 
        yield b 
        # print b 
        a, b = b, a + b 
        n = n + 1 

  yield 的做用就是把一個函數變成一個generator,帶有 yield 的函數再也不是一個普通函數,Python 解釋器會將其視爲一個生成器,如調用fab函數, 不會執行該函數,而是返回一個iterable迭代對象!nginx

  在for循環執行時,每次循環都會至關於執行生成器的next函數,纔開始執行fab函數的內部代碼,執行到yield b時,fab函數就返回一個迭代值,而後掛起。chrome

  下次迭代時,代碼從yield b的下一條語句繼續執行,而函數的本地變量看起來和上次中斷執行前是徹底同樣的,因而函數繼續執行,直到再次遇到yield。服務器

更多yield例子:併發

#!/usr/bin/python
def a():
    print ("do a() will not print out")
    yield 5
a()
print ("===============test a()")

def b():
    print ("list generator will in def , print here...")
    yield 5
g_obj = b()
print ("===============g_obj test b: %s" % g_obj)
print ("just generator obj, not in b def")
print ("list_g: %s" % list(g_obj))

def c():
    print ("next() will here... test generator next(), next attrbute not in python3, python2.6 is exist")
    yield 5
    print ("test generator next2")
g_obj = c()
print ("===============g_obj test c: %s" % g_obj)
#g_obj.next()
#print ("dir g_obj: %s " % dir(g_obj))


def d():
    global m
    global n
    print ("send() will here... test generator send()")
    m = yield 5
    print ("send input is m : %s" % m)
    n = yield 6
    print ("test generator send2")

g_obj = d()
print ("===============g_obj test d: %s" % g_obj)
s_return1 = g_obj.send(None)
s_return2 = g_obj.send("send twice")
print ("the next send input will be the result of last yield, just like m is : %s, s_return1 is : %s, s_return2 is : %s" % (m, s_return1, s_return2))
print ("not next send so n is undefind, n is : %s" % n)

運行結果:dom

===============test a()
===============g_obj test b: <generator object b at 0x7f740b7fc750>
just generator obj, not in b def
list generator will in def , print here...
list_g: [5]
===============g_obj test c: <generator object c at 0x7f740b7fc7e0>
===============g_obj test d: <generator object d at 0x7f740b7fc750>
send() will here... test generator send()
send input is m : send twice
the next send input will be the result of last yield, just like m is : send twice, s_return1 is : 5, s_return2 is : 6
Traceback (most recent call last):
  File "./yield0.py", line 40, in <module>
    print ("not next send so n is undefind, n is : %s" % n)
NameError: name 'n' is not defined

send用法說明:async

關於輸入:send的輸入是本次遇到yield時,先賦值給yield表達式的結果。有點難懂,詳細說明。函數

一、如m = yield 5,這個表達式,是分兩次yield完成的,第一次執行後一半,即返回5,下次send時,才執行前一半,即把後一次send的輸入賦值給m。oop

二、因此,第一次使用send,輸入必須是None,開啓生成器,由於本次遇到yield後,yield返回後,就完結了,並無一個執行到賦值給m的過程。m的初值是第二個send()輸入參數。

三、最後一個最後一個send,把輸入給了上一次yield表達式,因此最後一個n=yield 6,語句執行後,n是未定義的。

關於輸出:比較簡單,就是yield的結果。如s_return = send(None),因爲yield 5,因此s_return= 5

2  使用yield實現協程

舉例:生產者生產消息後,直接經過yield跳轉到消費者開始執行,待消費者執行完畢後,切換回生產者繼續生產。

#!/usr/bin/python

def consumer():
    r = ''
    while True:
        n = yield r
        if not n:
            print("not n...")
            return
        print('[CONSUMER] Consuming %s...' % n)
        r = '200 OK'

def produce(c):
    f = c.send(None)
    print('[PRODUCER] Consumer first return: %s' % f)
    n = 0
    while n < 2:
        n = n + 1
        print('[PRODUCER] Producing %s...' % n)
        r = c.send(n)
        print('[PRODUCER] Consumer return: %s' % r)
    c.close()

c = consumer()
produce(c)

運行結果:

[PRODUCER] Consumer first return: 
[PRODUCER] Producing 1...
[CONSUMER] Consuming 1...
[PRODUCER] Consumer return: 200 OK
[PRODUCER] Producing 2...
[CONSUMER] Consuming 2...
[PRODUCER] Consumer return: 200 OK

協程的說明:

注意到consumer函數是一個generator,把一個consumer傳入produce後:

  1. 首先調用c.send(None)啓動生成器;
  2. 而後,一旦生產了東西,經過c.send(n)切換到consumer執行;
  3. consumer經過yield拿到消息,處理,又經過yield把結果傳回;
  4. produce拿到consumer處理的結果,繼續生產下一條消息;
  5. produce決定不生產了,經過c.close()關閉consumer,整個過程結束。

整個流程無鎖,由一個線程執行,produce和consumer協做完成任務,因此稱爲「協程」,而非線程的搶佔式多任務。

3  yield from基本用法

從python3.3新增語法yield from,在python3.4中asyncio的微線程的實現依賴此語法。

先從generator中套generator的需求入手。

舉例:生成器調用子生成器,父生成器輸入什麼,調用完子生成器後,一樣返回什麼。

def i_yield_whatever_input_is():
    input = 0
    while True:
        print("1: before gi yield input=%s" % input)
        input = yield input
        print("2: after gi yield input=%s" % input)

def wrap_generator1():
    for i in i_yield_whatever_input_is():
        print("3: before g1 yield i=%s" % i)
        yield i

g = wrap_generator1()
print("4: after send None return: %s" % g.send(None))
print("4: after send 1 return: %s" % g.send(1))
print("4: after send 2 return: %s" % g.send(2))

未到達預期的運行結果:

1: before gi yield input=0
3: before g1 yield i=0
4: after send None return: 0
2: after gi yield input=None
1: before gi yield input=None
3: before g1 yield i=None
4: after send 1 return: None
2: after gi yield input=None
1: before gi yield input=None
3: before g1 yield i=None
4: after send 2 return: None

  顯然不是預期「輸入什麼,返回什麼」。因爲send的輸入到wrap_generator後,沒法輸入給子生成器,所以,子生成器i_yield_whatever_input_is的輸入是None,只能yield None。

  使用yield from,能夠將send的輸入,傳遞給子生成器,父生成器代碼修改以下:

def wrap_generator2():
    yield from i_yield_whatever_input_is()

g = wrap_generator2()
print("4: after send None return: %s" % g.send(None))
print("4: after send 1 return: %s" % g.send(1))
print("4: after send 2 return: %s" % g.send(2))

達到預期的運行結果:

1: before gi yield input=0
4: after send None return: 0
2: after gi yield input=1
1: before gi yield input=1
4: after send 1 return: 1
2: after gi yield input=2
1: before gi yield input=2
4: after send 2 return: 2

4 使用yield from實現asyncio

簡單的例子(兩個函數併發執行,函數內部的sleep不互相阻塞其它函數):

#!/usr/bin/python
import asyncio
import threading

@asyncio.coroutine
def hello():
    print("2.1 befor yield from asyncio sleep")
    r = yield from asyncio.sleep(2)
    print("2.1 after yield from asyncio sleep")

def hello2():
    print("2.2 befor yield from asyncio sleep")
    r = yield from asyncio.sleep(5)
    print("2.2 after yield from asyncio sleep")

loop = asyncio.get_event_loop()
print ("1. after get event loop")

#loop.run_until_complete(hello())

tasks = [hello2(), hello()]
loop.run_until_complete(asyncio.wait(tasks))
print ("2. after run")

loop.close()
print ("3. after close")

運行結果:

1. after get event loop
2.2 befor yield from asyncio sleep
2.1 befor yield from asyncio sleep
===等待兩個函數sleep返回===
2.1 after yield from asyncio sleep
2.2 after yield from asyncio sleep
2. after run
3. after close

複雜的例子(併發同時訪問多個WEB服務器):

#!/usr/bin/python
import asyncio

@asyncio.coroutine
def wget(host):
    print("wget %s..." % host)
    connect = asyncio.open_connection(host, 80)
    reader, writer = yield from connect
    header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host
    writer.write(header.encode('utf-8')) #向服務器發送請求
    yield from writer.drain()
    while True:
        line = yield from reader.readline() #讀取服務器返回的數據
        if line == b'\r\n':
            break
        print('%s header > %s' % (host, line.decode('utf-8').rstrip()))
    writer.close()

loop = asyncio.get_event_loop()
tasks = [wget(host) for host in ['www.baidu.com', 'www.sina.com''www.taobao.com']]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()

運行結果:併發訪問,服務器一旦返回,當即打印到屏幕。

wget www.baidu.com...
wget www.taobao.com...
wget www.sina.com...
www.baidu.com header > HTTP/1.1 200 OK
www.baidu.com header > Date: Fri, 12 Jun 2015 03:17:20 GMT
www.baidu.com header > Content-Type: text/html
www.baidu.com header > Content-Length: 14613
www.baidu.com header > Last-Modified: Wed, 03 Sep 2014 02:48:32 GMT
www.baidu.com header > Connection: Close
www.baidu.com header > Vary: Accept-Encoding
www.baidu.com header > Set-Cookie: BAIDUID=052DF57419E7322485FE496F7CFD60DF:FG=1; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com
www.baidu.com header > Set-Cookie: BIDUPSID=052DF57419E7322485FE496F7CFD60DF; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com
www.baidu.com header > Set-Cookie: PSTM=1434079040; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com
www.baidu.com header > Set-Cookie: BDSVRTM=0; path=/
www.baidu.com header > P3P: CP=" OTI DSP COR IVA OUR IND COM "
www.baidu.com header > Server: BWS/1.1
www.baidu.com header > X-UA-Compatible: IE=Edge,chrome=1
www.baidu.com header > Pragma: no-cache
www.baidu.com header > Cache-control: no-cache
www.baidu.com header > BDPAGETYPE: 1
www.baidu.com header > BDQID: 0x82714a2100005cd6
www.baidu.com header > BDUSERID: 0
www.baidu.com header > Accept-Ranges: bytes
www.sina.com header > HTTP/1.1 301 Moved Permanently
www.sina.com header > Server: nginx
www.sina.com header > Date: Fri, 12 Jun 2015 03:15:36 GMT
www.sina.com header > Content-Type: text/html
www.sina.com header > Location: http://www.sina.com.cn/
www.sina.com header > Expires: Fri, 12 Jun 2015 03:17:36 GMT
www.sina.com header > Cache-Control: max-age=120
www.sina.com header > Age: 104
www.sina.com header > Content-Length: 178
www.sina.com header > X-Cache: HIT from ja180-186.sina.com.cn
www.sina.com header > Connection: close
www.taobao.com header > HTTP/1.1 200 OK
www.taobao.com header > Server: Tengine
www.taobao.com header > Date: Fri, 12 Jun 2015 03:17:20 GMT
www.taobao.com header > Content-Type: text/html; charset=gbk
www.taobao.com header > Connection: close
www.taobao.com header > Vary: Accept-Encoding
www.taobao.com header > Set-Cookie: CAT=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0
www.taobao.com header > Set-Cookie: thw=cn; Path=/; Domain=.taobao.com; Expires=Sat, 11-Jun-16 03:17:20 GMT;
相關文章
相關標籤/搜索