def consumer():
r = ''
while True:
n = yield r
if not n:return
print('consuming the event %s'%n)
r = '200 OK'
def produce(c):
c.send(None)
for n in range(1,6):
print('producing event %s'%n)
r = c.send(n)
print('the consumer response %s'%r)
c.close()
c = consumer()
produce(c)
import asyncio,sys,time
@asyncio.coroutine
def hello():
time.sleep(3)
print("Hello world!")
# 异步调用asyncio.sleep(1):
r = yield from asyncio.sleep(2)
print("Hello again!")
# 获取EventLoop:
loop = asyncio.get_event_loop()
# 执行coroutine
loop.run_until_complete(asyncio.wait([hello() for i in range(3)]))
loop.close()
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()))
# Ignore the body, close the socket
writer.close()
loop = asyncio.get_event_loop()
tasks = [wget(host) for host in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
When the size of the transport buffer reaches the high-water limit (the protocol is paused), block until the size of the buffer is drained down to the low-water limit and the protocol is resumed. When there is nothing to wait for, the yield-from continues immediately.