[英]Python - asyncio - Wait for a future inside a callback
Here is my code, I want my_reader
to wait maximum 5 seconds for a future then do something with the my_future.result()
. 这是我的代码,我希望
my_reader
等待最多5秒钟,以备将来使用,然后对my_future.result()
。 Please note that my_reader
is not a coroutine , it is a callback . 请注意,
my_reader
不是 协程 ,它是一个回调 。
import asyncio, socket
sock = ...
async def my_coroutine():
...
def my_reader():
my_future = asyncio.Future()
...
# I want to wait (with a timeout) for my_future
loop = asyncio.get_event_loop()
loop.add_reader(sock, my_reader)
loop.run_forever()
loop.close()
I don't want to use either: 我不想使用:
AbstractEventLoop.create_datagram_endpoint()
AbstractEventLoop.create_connection()
The socket I have is returned from another module and I have to read packets with a given size. 我拥有的套接字是从另一个模块返回的,我必须读取给定大小的数据包。 The transfer must happen under 5 seconds.
转移必须在5秒内完成。
How to wait for a future inside a callback? 如何在回调中等待将来?
Sorry, waiting in callbacks is impossible. 抱歉,不可能在回调中等待。 Callback should be executed instantly by definition -- otherwise event loop hangs on callback execution period.
回调应按定义立即执行-否则事件循环将在回调执行期间挂起。
Your logic should be built on coroutines but low-level on_read callback may inform these coroutines by setting a value of future. 您的逻辑应该建立在协程上,但是低级on_read回调可能会通过设置future的值来通知这些协程。
See aiopg.connection for inspiration. 请参阅aiopg.connection以获取灵感。 The callback is named
Connection._ready
. 回调名为
Connection._ready
。
You should run the coroutine separately and send data to it from the callback via Queue. 您应该分别运行协程,并通过Queue从回调中向其发送数据。
Look on this answer: 看这个答案:
https://stackoverflow.com/a/29475218/1112457 https://stackoverflow.com/a/29475218/1112457
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.