Python 异步协同路由

Python 异步协同路由,python,python-3.x,coroutine,python-asyncio,Python,Python 3.x,Coroutine,Python Asyncio,我认为我已经摸索出了与David Beazley的非常好的协同程序,但我不能完全将其与中描述的新语法相协调 在演示中,他解释了如何将协同路由视为推送到而不是从类似的生成器中拉出的管道 例如: # 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.

我认为我已经摸索出了与David Beazley的非常好的协同程序,但我不能完全将其与中描述的新语法相协调

在演示中,他解释了如何将协同路由视为推送到而不是从类似的生成器中拉出的管道

例如:

# 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()
coroutine?我还没有看到一个例子,在这个例子中,协程被推到使用这种新语法。有可能吗?

您所拥有的不是
asyncio
模块和/或PEP-492意义上的协同程序。正如政治公众人物本身所说:

[此PEP]仅与使用
产量
作为调度程序信号的协同路由类型相关,指示协同路由将等待事件(如IO)完成

  • 您的示例中没有涉及调度程序(事件循环),并且
  • 协同程序不使用
    yield
    仅作为“发送给调度程序的信号”;它实际上是在用它来读取数据

  • 这实际上与
    asyncio
    没有太多关系。如果它不使用事件循环,那么从
    asyncio
    模块所提供的意义上讲,它就不是真正的异步的。这个例子是关于传统的协同路由,其中协同路由决定应该运行哪个其他协同路由,以及应该向它发送什么值。这是很难维护的,并且通常是不必要的,因此异步协同路由的行为不同。他们所能做的就是放弃自己的跑步权利,并传递一个等待已久的未来对象,该对象代表的任务应该是这个协同过程的延续。还有一个事件循环安排了所有这些,它运行并在等待完成时将正确的值发送给协程。