异步协程

Asyncio coroutines

我以为我已经和 David Beazley 的协程很好地了解了 presentation but I can't reconcile it fully with the new syntax described in PEP-492

在演示文稿中,他解释了如何将协程视为像生成器中那样被推入而不是被拉出的管道。

例如:

# cofollow.py
#
# A simple example showing how to hook up a pipeline with
# coroutines.   To run this, you will need a log file.
# Run the program logsim.py in the background to get a data
# source.

from coroutine import coroutine

# A data source.  This is not a coroutine, but it sends
# data into one (target)

import time
def follow(thefile, target):
    thefile.seek(0,2)      # Go to the end of the file
    while True:
         line = thefile.readline()
         if not line:
             time.sleep(0.1)    # Sleep briefly
             continue
         target.send(line)

# A sink.  A coroutine that receives data

@coroutine
def printer():
    while True:
         line = (yield)
         print line,

# Example use
if __name__ == '__main__':
    f = open("access-log")
    follow(f,printer())

如何使用这一新语法实现 printer() 协程?我还没有看到协程被推送到使用这种新语法的示例。可能吗?

你所拥有的不是 asyncio 模块 and/or PEP-492 意义上的协程。正如 PEP 本身所说:

[This PEP] is relevant only to the kind of coroutine that uses yield as a signal to the scheduler, indicating that the coroutine will be waiting until an event (such as IO) is completed.

  1. 您的示例中没有涉及调度程序(事件循环),并且
  2. 协程不使用 yield 仅 "as a signal to the scheduler";它真的是用它来读取数据。