From f94bf4fd8d80e6d0e17d061121dfc9da47ee2b47 Mon Sep 17 00:00:00 2001 From: limil Date: Mon, 28 Oct 2024 09:26:56 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8F=90=E4=BA=A4=E6=B5=8B=E8=AF=95=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- test.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 test.py diff --git a/test.py b/test.py new file mode 100644 index 0000000..24855a6 --- /dev/null +++ b/test.py @@ -0,0 +1,42 @@ +import asyncio +import threading +import nest_asyncio + + + +async def aoutput(output): + print(output) + +# 定义一个函数来启动事件循环 +def start_event_loop(mainloop, newloop): + asyncio.set_event_loop(newloop) + newloop.run_forever() + +async def myinput(newloop): + future = asyncio.run_coroutine_threadsafe(asyncio.con(input("input")), newloop) + return await asyncio.wrap_future(future) + +async def myoutput(newloop, output): + future = asyncio.run_coroutine_threadsafe(aoutput(output), newloop) + await asyncio.wrap_future(future) + +async def main(mainloop, newloop): + while True: + res = await myinput(newloop) + await myoutput(newloop, res) + +if __name__ == "__main__": + nest_asyncio.apply() + + # 创建一个新的事件循环 + main_loop = asyncio.get_event_loop() + new_loop = asyncio.new_event_loop() + + # 使用 threading 模块创建一个新线程,并在该线程中运行事件循环 + thread = threading.Thread(target=start_event_loop, args=(main_loop, new_loop,)) + thread.start() + + asyncio.run(main(main_loop, new_loop)) + + # 等待线程完成 + thread.join()