简体   繁体   English

从事件流中运行异步协程

[英]Running asyncio coroutine out of the event flow

I'm having issues where my call to api.say() fails. 我在调用api.say()失败时遇到问题。 I understand its a coroutine and needs to be yielded from but is that valid if my print_all is a standard function. 我了解它的协程,需要从中产生,但是如果我的print_all是标准函数,那是有效的。

What is the correct way to structure this example? 构造此示例的正确方法是什么?

Please assume that the Client isn't changeable, only the code in my example. 请假设客户端是不可更改的,仅是示例中的代码。

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

The Client API might handle callbacks that are coroutines too ie, you can convert print_all() into a coroutine (prepend async before def , add await before api.say() ). 客户端API可能也处理作为协程的回调,即,您可以将print_all()转换为协程(在def之前添加async ,在api.say()之前添加await )。

Otherwise, you could call asyncio.ensure_future(api.say(..)) to schedule the coroutine. 否则,您可以调用asyncio.ensure_future(api.say(..))来安排协程。 It assumes that loop.run_until_complete(api.run()) won't return before api.say() is done ie, there is loop.run_forever() equivalent in your program or you wait for all tasks -- either collected explicitly or implicitly ( asyncio.Task.all_tasks() ). 它假定loop.run_until_complete(api.run())api.say()完成之前不会返回,即程序中有loop.run_forever()等效项,或者您等待所有任务-无论是显式收集还是隐式( asyncio.Task.all_tasks() )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM