問題描述
啟動兩個 CPU 阻塞偵聽器並等待其中一個完成 (Starting two cpu blocking listeners and wait until one of them finishes)
我正在嘗試同時收聽電報或不和諧消息,無論第一個消息是什麼。對於 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()
對於不和諧,我使用的是 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) 使用python進程,不過不知道怎麼做,等第一個返回值。
參考解法
方法 1:
You don't really need to have them in parallel for simultaneously, it is easier to have them concurrent (but still simultaneosly waiting). You can use Python Thread‑based parallelism instead.