pythonyield⽤法举例说明
1 yield基本⽤法
典型的例⼦:
斐波那契(Fibonacci)數列是⼀个⾮常简单的递归数列,除第⼀个和第⼆个数外,任意⼀个数都可由前两个数相加得到。1 2 3 5 8……
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迭代对象!
在for循环执⾏时,每次循环都会相当于执⾏⽣成器的next函数,才开始执⾏fab函数的内部代码,执⾏到yield b时,fab函数就返回⼀个迭代值,然后挂起。
下次迭代时,代码从yield b的下⼀条语句继续执⾏,⽽函数的本地变量看起来和上次中断执⾏前是完全⼀样的,于是函数继续执⾏,直到再次遇到yield。
更多yield例⼦:
#!/usr/bin/python
python新手代码useriddef a():
print ("do a() will not print out")
yield 5
a()
print ("===============test a()")
def b():
print ("list generator will in def , ")
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() 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)
#()
#print ("dir g_obj: %s " % dir(g_obj))
def d():
global m
global n
print ("send() 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)
运⾏结果:
===============test a()
===============g_obj test b: <generator object b at 0x7f740b7fc750>
just generator obj, not in b def
list generator will in def ,
list_g: [5]
===============g_obj test c: <generator object c at 0x7f740b7fc7e0>
===============g_obj test d: <generator object d at 0x7f740b7fc750>
send() 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⽤法说明:
关于输⼊:send的输⼊是本次遇到yield时,先赋值给yield表达式的结果。有点难懂,详细说明。
1、如m = yield 5,这个表达式,是分两次yield完成的,第⼀次执⾏后⼀半,即返回5,下次send时,才执⾏前⼀半,即把后⼀次send的输⼊赋值给m。
2、所以,第⼀次使⽤send,输⼊必须是None,开启⽣成器,因为本次遇到yield后,yield返回后,就完结了,并没有⼀个执⾏到赋值给m的过程。m的初值是第⼆个send()输⼊参数。
3、最后⼀个最后⼀个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("")
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]
[CONSUMER]
[PRODUCER] Consumer return: 200 OK
[PRODUCER]
[CONSUMER]
[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
@utine
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 = _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
@utine
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.de('utf-8')) #向服务器发送请求
yield from writer.drain()
while True:
line = yield adline() #读取服务器返回的数据
if line == b'\r\n':
break
print('%s header > %s' % (host, line.decode('utf-8').rstrip()))
writer.close()
loop = _event_loop()
tasks = [wget(host) for host in ['www.baidu', 'www.sina','www.taobao']]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
运⾏结果:并发访问,服务器⼀旦返回,⽴即打印到屏幕。
wget
wget
wget
www.baidu header > HTTP/1.1 200 OK
www.baidu header > Date: Fri, 12 Jun 2015 03:17:20 GMT
www.baidu header > Content-Type: text/html
www.baidu header > Content-Length: 14613
www.baidu header > Last-Modified: Wed, 03 Sep 2014 02:48:32 GMT
www.baidu header > Connection: Close
www.baidu header > Vary: Accept-Encoding
www.baidu header > Set-Cookie: BAIDUID=052DF57419E7322485FE496F7CFD60DF:FG=1; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu www.baidu header > Set-Cookie: BIDUPSID=052DF57419E7322485FE496F7CFD60DF; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu www.baidu header > Set-Cookie: PSTM=1434079040; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu
www.baidu header > Set-Cookie: BDSVRTM=0; path=/
www.baidu header > P3P: CP=" OTI DSP COR IVA OUR IND COM "
www.baidu header > Server: BWS/1.1
www.baidu header > X-UA-Compatible: IE=Edge,chrome=1
www.baidu header > Pragma: no-cache
www.baidu header > Cache-control: no-cache
www.baidu header > BDPAGETYPE: 1
www.baidu header > BDQID: 0x82714a2100005cd6
www.baidu header > BDUSERID: 0
www.baidu header > Accept-Ranges: bytes
www.sina header > HTTP/1.1 301 Moved Permanently
www.sina header > Server: nginx
www.sina header > Date: Fri, 12 Jun 2015 03:15:36 GMT
www.sina header > Content-Type: text/html
www.sina header > Location: www.sina/
www.sina header > Expires: Fri, 12 Jun 2015 03:17:36 GMT
www.sina header > Cache-Control: max-age=120
www.sina header > Age: 104
www.sina header > Content-Length: 178
www.sina header > X-Cache: HIT from ja180-186.sina
www.sina header > Connection: close
www.taobao header > HTTP/1.1 200 OK
www.taobao header > Server: Tengine
www.taobao header > Date: Fri, 12 Jun 2015 03:17:20 GMT
www.taobao header > Content-Type: text/html; charset=gbk
www.taobao header > Connection: close
www.taobao header > Vary: Accept-Encoding
www.taobao header > Set-Cookie: CAT=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0
www.taobao header > Set-Cookie: thw=cn; Path=/; Domain=.taobao; Expires=Sat, 11-Jun-16 03:17:20 GMT;
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论