按类型获取控制台用户输入的字符,一个字符一个字符 [英] Get console user input as typed, char by char

查看:138
本文介绍了按类型获取控制台用户输入的字符,一个字符一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Elixir中有一个控制台应用程序.我需要按按键来解释用户的输入.例如,我需要将"q"视为结束会话的命令,而无需用户明确按又称回车".

I have a console application in Elixir. I need to interpret user’s input on by keypress basis. For instance, I need to treat "q" as a command to end the session, without user to explicitly press a.k.a. "carriage return."

IO.getn/2 令人惊讶地等待将被按下,以缓冲输入(我几乎可以肯定,该缓冲是由控制台本身完成的,但是man stty并没有提供任何帮助/标志来关闭缓冲.)

IO.getn/2 surprisingly waits for the to be pressed, buffering an input (I am nearly sure, that this buffering is done by console itself, but man stty does not provide any help/flag to turn buffering off.)

Mix.Utils 使用无限循环隐藏用户输入(基本上每隔1毫秒发送一次退格控制序列到控制台),IEx代码将对标准erlang的io的调用包装起来,这提供了在 Tab 上设置回调的唯一功能(用于自动完成) )

Mix.Utils use the infinite loop to hide user input (basically sending backspace control sequence to console every 1ms,) IEx code wraps calls to standard erlang’s io, that provides the only ability to set a callback on Tab (for autocompletion.)

我的猜测是我必须使用 Port ,将其附加到:stdin并生成一个进程来监听输入.不幸的是,我坚持尝试实现后者,因为我需要附加到当前正在运行的控制台,而不是为其他进程创建新端口(因为它是

My guess would be I have to use Port, attach it to :stdin and spawn a process to listen to the input. Unfortunately, I am stuck with trying to implement the latter, since I need to attach to the currently running console, not create a new port to some other process (as it is perfectly described here.)

我在将Port附加到当前进程的:stdin(在Port.list/0中列出了btw)时是否缺少明显的东西,还是应该将整个3管道体系结构构建为将输入的内容重定向到:stdin以及我的程序想要将puts重定向到:stdout的任何内容?

Am I missing something obvious on how am I to attach a Port to the current process’ :stdin (which is btw listed in Port.list/0,) or should I’ve built the whole 3-piped architecture to redirect what’s typed to :stdin and whatever my program wants to puts to :stdout?

推荐答案

您的程序无法获取密钥,因为在Linux上,终端默认为

Your program doesn't get the keys because on Linux, the terminal is by default in cooked mode, which buffers all keypresses until Return is pressed.

您需要将终端切换到原始模式,该模式会在按键发生时立即将按键发送到应用程序.没有跨平台可以做到这一点.

You need to switch your terminal to raw mode, which sends the keypresses to the application as soon as they happen. There's no cross-platform to do this.

对于类似Unix的系统,存在ncurses,其中包含应检查的长生不老药绑定: https://github .com/jfreeze/ex_ncurses .它甚至有一个示例可以做您想要的.

For unix-like systems there's ncurses, which has an elixir binding that you should check out: https://github.com/jfreeze/ex_ncurses. It even has an example to do what you want.

这篇关于按类型获取控制台用户输入的字符,一个字符一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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