【问题标题】:Starting two cpu blocking listeners and wait until one of them finishes启动两个 cpu 阻塞侦听器并等待其中一个完成
【发布时间】:2021-05-15 01:35:45
【问题描述】:

我正在尝试同时收听电报或不和谐消息,无论是第一个进来的消息。对于 Telegram,我正在使用 Telethon:

async def listentg():
    tgclient = TelegramClient('anon', conntg.tg_api_id, conntg.tg_api_hash)
    @tgclient.on(events.NewMessage(chats=conntg.canaltg, pattern=patternmatch))
    async def tg_event_handler(event):
        print("Telegram message listened")
        await tgclient.disconnect()
    await tgclient.start()
    await tgclient.run_until_disconnected()

对于 Discord,我使用的是 Discum

async def listendc():
    dcclient = discum.Client(token=conndc.tokendc, log=False)
    @dcclient.gateway.command
    def dc_event_handler(resp):
        if resp.event.message:
            print("Discord message listened")
            dcclient.gateway.close()
    dcclient.gateway.run()

我知道要同时运行 CPU 阻塞代码,我必须 (https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_in_executor) use python processes,但我不知道该怎么做,只是等待第一个返回值。

【问题讨论】:

  • 如果discum 阻塞了整个线程,那么是的,你需要loop.run_in_executor。使您的def listendc 非异步并使用run_in_executor 就足够了;你遇到了什么问题?

标签: python python-3.x discord telethon


【解决方案1】:

您实际上并不需要同时让它们并行,让它们并发更容易(但仍然同时等待)。您可以改用Python Thread-based parallelism

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-06
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 2020-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多