【问题标题】:Running asyncio coroutine out of the event flow在事件流之外运行 asyncio 协程
【发布时间】:2016-01-06 19:36:36
【问题描述】:

我遇到了调用 api.say() 失败的问题。我理解它是一个协程,需要从中产生,但如果我的 print_all 是一个标准函数,它是否有效。

构建这个例子的正确方法是什么?

请假设客户端是不可更改的,只有我的示例中的代码。

from .client import Client
import asyncio

api = Client()
login = ('', '')

def print_all(b=None, m=None):
    print("Buffer!", b)
    print("Message", m)

    if b and m:
        if b.name == 'bat':
            print("-sending to", b)
            api.say(b, "Hey yo."):    # <----


def main():
    api.login(*login)
    api.register_message_callback(print_all)
    api.register_state_callback(print_all)

    loop = asyncio.get_event_loop()
    loop.run_until_complete(api.run())
    loop.close()

if __name__ == '__main__':
    main()

【问题讨论】:

    标签: python python-3.x coroutine python-asyncio


    【解决方案1】:

    客户端 API 也可能处理作为协程的回调,即,您可以将 print_all() 转换为协程(在 def 之前添加 async,在 api.say() 之前添加 await)。

    否则,您可以调用asyncio.ensure_future(api.say(..)) 来安排协程。它假定loop.run_until_complete(api.run())api.say() 完成之前不会返回,即您的程序中有loop.run_forever() 等效项,或者您等待所有任务——无论是显式还是隐式收集(asyncio.Task.all_tasks())。

    【讨论】:

    • 感谢asyncio.ensure_future(api.say(..)) 解决了这个问题。我的客户没有将回调作为协程处理,因此 .ensure_future(...) 将其整理出来。
    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    • 2019-05-07
    • 2020-04-14
    • 1970-01-01
    相关资源
    最近更新 更多