Python asyncio:包含在Task中的第二个协同程序未安排(但首先是)

时间:2017-03-13 16:53:23

标签: python python-asyncio coroutine

我已根据asyncio.Protocol编写了一个Echo客户端。 我感兴趣的是在data_received收到一些数据时触发回调。

我正在尝试通过在data_received中创建协同程序中的Task来实现此目的,然后我通过add_done_callback进行回调。

这是客户的代码:

import asyncio

class EchoClientProtocol(asyncio.Protocol):

    def __init__(self, loop):
        self.loop = loop
        self.tasks = None

        # To be initialised upon connection
        self.transport = None

    def send(self, msg):
        print('>', msg)
        self.transport.write(msg)

    def connection_made(self, transport):
        self.transport = transport
        self.logon()

    def data_received(self, msg):
        print('<', msg)
        if msg == b'logon':
            task = self.loop.create_task(next(self.tasks)())
            task.add_done_callback(next(self.tasks))
        else:
            try:
                task = self.loop.create_task(next(self.tasks)())
                task.add_done_callback(next(self.tasks))
            except StopIteration:
                print('no more messages')
                return

    def eof_received(self):
        """Triggered when the other end signals it won't send any more data"""
        print('EOF received')

    def connection_lost(self, exc):
        """Triggered when connection is lost"""
        print('Exception: %s', exc)
        self.loop.stop()

    def logon(self):
        self.send(b'logon')

主要看起来像这样:

def main():
    loop = asyncio.get_event_loop()
    EchoClient = EchoClientProtocol(loop)

    # access recv and send here
    first_msg = b'message 1'
    second_msg = b'message 2'

    @asyncio.coroutine
    def first():
        yield EchoClient.send(first_msg)

    @asyncio.coroutine
    def second(*a):
        yield EchoClient.send(second_msg)

    def tasks():
        yield first
        yield second

    EchoClient.tasks = tasks()

    loop = asyncio.get_event_loop()
    coro = loop.create_connection(lambda: EchoClient, '127.0.0.1', 2000)
    loop.run_until_complete(coro)
    loop.run_forever()
    loop.close()

if __name__ == '__main__':
    main()

这是我运行客户端时的输出(它假设一个Echo服务器在端口2000上运行 - 如果你没有一个,那就可以解决问题:socat TCP4-LISTEN:2000,fork EXEC:cat):

jir@klo01 $ python3 echo_client_asyncio3.py 
> b'logon'
< b'logon'
> b'message 1'
< b'message 1'
no more messages
^CTraceback (most recent call last):
  File "echo_client_asyncio3.py", line 76, in <module>
    main()
  File "echo_client_asyncio3.py", line 72, in main
    loop.run_forever()
  File "/home/jir/apps/lib/python3.6/asyncio/base_events.py", line 421, in run_forever
    self._run_once()
  File "/home/jir/apps/lib/python3.6/asyncio/base_events.py", line 1389, in _run_once
    event_list = self._selector.select(timeout)
  File "/home/jir/apps/lib/python3.6/selectors.py", line 445, in select
    fd_event_list = self._epoll.poll(timeout, max_ev)
KeyboardInterrupt

如您所见,第一个协程已正确安排:发送和接收logon,并发送和接收message1。但是,message2似乎无法安排。

知道我在这里做错了吗?

1 个答案:

答案 0 :(得分:1)

task.add_done_callback(f)接受常规功能,而不是协程。

假设有以下变化:

def tasks():
    yield first()
    yield second()

这将有效:

    task = self.loop.create_task(next(self.tasks))
    next_task = next(self.tasks)
    task.add_done_callback(
        lambda fut: self.loop.create_task(next_task))

请记住,您可以使用包装器任务,而不是使用add_done_callback

async def first_and_second():
    await first()
    await second()