gpt4 book ai didi

Python异步: second coroutine wrapped in a Task is not scheduled (but first is)

转载 作者:太空宇宙 更新时间:2023-11-03 15:32:50 25 4
gpt4 key购买 nike

我编写了一个基于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 :猫):

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 似乎从未得到安排。

知道我在这里做错了什么吗?

最佳答案

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()

关于Python异步: second coroutine wrapped in a Task is not scheduled (but first is),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42769177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com