简体   繁体   English

将 python asyncio 与 pyee Event Emitter 结合使用

[英]Combine python asyncio with pyee Event Emitter

I am trying use the AsyncIOEventEmitter from the pyee library without success.我正在尝试使用pyee 库中的AsyncIOEventEmitter但没有成功。 For some reason the emitted event "Hi" never reaches the async_handler to complete the asyncio future.由于某种原因,发出的事件“Hi”永远不会到达async_handler以完成 asyncio 未来。 I also did not find proper examples online.我也没有在网上找到合适的例子。 Additionally I tried providing the current event and using a new event loop for the AsyncIOEventEmitter , but both yields the same result.此外,我尝试提供当前事件并为AsyncIOEventEmitter使用新的事件循环,但两者都产生相同的结果。

Can someone help me out?有人可以帮我吗? Example unit test below:下面的示例单元测试:

import asyncio
import logging
import pytest
from pyee import AsyncIOEventEmitter

LOG = logging.getLogger(__name__)

@pytest.mark.asyncio
async def test_setup(event_loop):
    LOG.info("1 - start")
    event_emitter = AsyncIOEventEmitter(asyncio.new_event_loop())

    # Create a new Future object.
    future_result = event_loop.create_future()
    LOG.info("2 - emit event")
    event_emitter.emit("event", "Hi")

    @event_emitter.on("event")
    async def async_handler(message):
        LOG.info(">>> %s", message)
        future_result.set_result(message)
        return future_result

    # Wait until *future_result* has a result and print it.
    LOG.info(await future_result)

Thanks!谢谢!

ok figured it out, the async_handler method must be defined earlier in the test...好的,想通了, async_handler方法必须在测试的早期定义......

This worked now:这现在有效:

"""Event emitter playground"""
import asyncio
import logging
import pytest
from pyee import AsyncIOEventEmitter

LOG = logging.getLogger(__name__)


@pytest.mark.asyncio
async def test_setup(event_loop):
    """Receive event from emitter and complete future!"""
    LOG.info("1 - start")
    event_emitter = AsyncIOEventEmitter(asyncio.new_event_loop())

    @event_emitter.on("event")
    def async_handler(message):
        LOG.info(">>> %s", message)
        future_result.set_result(message)

    future_result = event_loop.create_future()
    LOG.info("2 - emit event")
    event_emitter.emit("event", "Hi")

    LOG.info(await future_result)

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

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