异步IO
协程
def odd():
n=1
while True:
yield n
n+=2
odd_num = odd()
count = 0
for o in odd_num:
if count >=5: break
print(o)
count +=1
1
3
5
7
9
help(odd_num)
Help on generator object:
odd = class generator(object)
| Methods defined here:
|
| __del__(...)
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __next__(self, /)
| Implement next(self).
|
| __repr__(self, /)
| Return repr(self).
|
| close(...)
| close() -> raise GeneratorExit inside generator.
|
| send(...)
| send(arg) -> send 'arg' into generator,
| return next yielded value or raise StopIteration.
|
| throw(...)
| throw(typ[,val[,tb]]) -> raise exception in generator,
| return next yielded value or raise StopIteration.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| gi_code
|
| gi_frame
|
| gi_running
|
| gi_yieldfrom
| object being iterated by yield from, or None
def consumer():
r=''
while True:
n = yield r
print('[CONSUMER] Consuming %s' %n)
r='200 OK'
def produce(c):
#启动generator
c.send(None)
n = 0
while n<5:
n=n+1
print('[PRODUCER] Producing %s...' % n)
#将n传给cosumer()里的n,最后运行返回r
r = c.send(n)
print('[PRODUCER] Consumer return: %s' % r)
c.close()
c = consumer()
produce(c)
[PRODUCER] Producing 1...
[CONSUMER] Consuming 1
[PRODUCER] Consumer return: 200 OK
[PRODUCER] Producing 2...
[CONSUMER] Consuming 2
[PRODUCER] Consumer return: 200 OK
[PRODUCER] Producing 3...
[CONSUMER] Consuming 3
[PRODUCER] Consumer return: 200 OK
[PRODUCER] Producing 4...
[CONSUMER] Consuming 4
[PRODUCER] Consumer return: 200 OK
[PRODUCER] Producing 5...
[CONSUMER] Consuming 5
[PRODUCER] Consumer return: 200 OK
asyncio
def writer():
# 读取send传进的数据,并模拟写进套接字或文件
while True:
w = (yield) # w接收send传进的数据
print('>> ', w)
def writer_wrapper(coro):
# TBD
pass
w = writer()
wrap = writer_wrapper(w)
w.send(None) # 生成器准备好接收数据
for i in range(4):
w.send(i)
>> 0
>> 1
>> 2
>> 3
def writer():
# 读取send传进的数据,并模拟写进套接字或文件
while True:
w = (yield) # w接收send传进的数据
print('>> ', w)
def writer_wrapper(coro2):
#所有发送(send)到wrap的数都被直接发送到coro2
yield from coro2
w = writer()
wrap = writer_wrapper(w)
wrap.send(None)
for i in range(4):
wrap.send(i)
>> 0
>> 1
>> 2
>> 3
def writer_wrapper(coro1):
coro1.send(None) # 生成器准备好接收数据
while True:
try:
x = (yield) # x接收send传进的数据
coro1.send(x) # 然后将x在send给writer子生成器
except StopIteration: # 处理子生成器返回的异常
pass