cxx*_*xxl 4 python python-asyncio
我正在尝试编写一个并发的Python程序,asyncio它也接受键盘输入。当我尝试关闭程序时出现问题。由于键盘输入最终是通过 完成的sys.stdin.readline,因此该函数仅在我按下 后返回ENTER,无论我是stop()事件循环还是cancel()函数的Future。
有什么办法可以提供asyncio可以取消的键盘输入吗?
这是我的 MWE。它将接受键盘输入 1 秒,然后stop():
import asyncio
import sys
async def console_input_loop():
while True:
inp = await loop.run_in_executor(None, sys.stdin.readline)
print(f"[{inp.strip()}]")
async def sleeper():
await asyncio.sleep(1)
print("stop")
loop.stop()
loop = asyncio.get_event_loop()
loop.create_task(console_input_loop())
loop.create_task(sleeper())
loop.run_forever()
Run Code Online (Sandbox Code Playgroud)
问题在于执行者坚持确保在程序终止时所有正在运行的 future 都已完成。但在这种情况下,您实际上想要一个“不干净”的终止,因为没有可移植的方法来取消正在进行的read()或异步访问sys.stdin。
取消 future 没有任何效果,因为concurrent.futures.Future.cancel一旦回调开始执行,它就是一个无操作。避免不必要的等待的最佳方法是run_in_executor首先避免并生成您自己的线程:
async def ainput():
loop = asyncio.get_event_loop()
fut = loop.create_future()
def _run():
line = sys.stdin.readline()
loop.call_soon_threadsafe(fut.set_result, line)
threading.Thread(target=_run, daemon=True).start()
return await fut
Run Code Online (Sandbox Code Playgroud)
该线程是手动创建的,并标记为“守护进程”,因此没有人会在程序关闭时等待它。结果,使用ainput而不是按run_in_executor(sys.stdin.readline)预期终止的代码变体:
async def console_input_loop():
while True:
inp = await ainput()
print(f"[{inp.strip()}]")
# rest of the program unchanged
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1940 次 |
| 最近记录: |