python - 用 asyncio 听按键

标签 python python-3.x python-asyncio

有人可以提供一个代码示例,它使用 asynio 以非阻塞方式监听按键,并在每次点击时将键码放在控制台中吗?

这不是关于某些图形工具包的问题

最佳答案

因此,Andrea Corbellini 提供的链接是对问题的巧妙而彻底的解决方案,但也相当复杂。如果您只想提示您的用户输入一些输入(或模拟 raw_input),我更愿意使用更简单的解决方案:

import sys
import functools
import asyncio as aio

class Prompt:
    def __init__(self, loop=None):
        self.loop = loop or aio.get_event_loop()
        self.q = aio.Queue()
        self.loop.add_reader(sys.stdin, self.got_input)

    def got_input(self):
        aio.ensure_future(self.q.put(sys.stdin.readline()), loop=self.loop)

    async def __call__(self, msg, end='\n', flush=False):
        print(msg, end=end, flush=flush)
        return (await self.q.get()).rstrip('\n')

prompt = Prompt()
raw_input = functools.partial(prompt, end='', flush=True)

async def main():
    # wait for user to press enter
    await prompt("press enter to continue")

    # simulate raw_input
    print(await raw_input('enter something:'))

loop = aio.get_event_loop()
loop.run_until_complete(main())
loop.close()

编辑:我删除了循环参数表单 Queue,因为它在 3.10 中被删除了。

此外,这些天我使用结构化并发(trio),如果有人好奇这在 trio 中很容易做到:

import trio, sys
  
async def main():
    async with trio.lowlevel.FdStream(sys.stdin.fileno()) as stdin:
            async for line in stdin:
                if line.startswith(b'q'):
                    break
                print(line)


trio.run(main)

关于python - 用 asyncio 听按键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35223896/

相关文章:

python - 使用格式模式将字符串反序列化为值

python - 如何缓存和迭代未知大小的数据集?

python - 运行时警告 : coroutine was never awaited

python - 将函数置于后台

python - 将按钮释放视为键盘中断 tkinter

Python Unicode 导出到 CSV,删除 'u' 字符

python - 无法使用 pytorch 进行预测 [MNIST]

python - 高效精准的欧式距离计算

python - 如何在 Python 中添加到文件末尾?

python - 取消异步上下文管理器