【发布时间】:2013-09-07 19:13:52
【问题描述】:
我正在根据http://www.dabeaz.com/coroutines/Coroutines.pdf尝试协程管道
问题是,我怎样才能从sink 中获得价值而不是仅仅打印它?
以这段代码为例
def coroutine(func):
def start(*args, **kwargs):
cr = func(*args, **kwargs)
next(cr)
return cr
return start
@coroutine
def produce(target):
while True:
n = (yield)
target.send(n*10)
@coroutine
def sink():
try:
while True:
n = (yield)
print(n)
except GeneratorExit:
pass
sk = sink()
pipe = produce(sink())
使用此代码,我得到:
>>> pipe.send(10)
100
然后我想获取返回值而不是打印它,我尝试从接收器产生:
@coroutine
def sink():
try:
while True:
yield (yield)
except GeneratorExit:
pass
但它似乎不起作用,pipe.send(10) 仍然返回 None 而不是生成器。
那我该如何获取返回值呢?
【问题讨论】:
标签: python generator coroutine