我正在按照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
然后我希望获得返回值而不是将其打印出来,我尝试使用yield from sink:
@coroutine
def sink():
try:
while True:
yield (yield)
except GeneratorExit:
pass
但是似乎没有起作用,pipe.send(10)
仍然返回None
而不是生成器。
那么我该如何获取返回值呢?