使用 asyncio 收听按键 [英] Listen to keypress with asyncio

查看:42
本文介绍了使用 asyncio 收听按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Can somebody provide a sample of code which listen to keypress in nonblocking manner with asynio and put the keycode in console on every click?

这不是一些图形工具包的问题

It's not a question about some graphical toolkit

推荐答案

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

So the link provided by Andrea Corbellini is a clever and thorough solution to the problem, but also quite complicated. If all you want to do is prompt your user to enter some input (or simulate raw_input), I prefer to use the much simpler solution:

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 中被删除了.

I removed the loop parameter form Queue as it is removed in 3.10.

此外,最近我使用结构化并发(三重奏),如果有人好奇,这在三重奏中很容易做到:

Also, these days I use structured concurrency (trio), and if anyone is curious this is pretty easy to do in 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)

这篇关于使用 asyncio 收听按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆