英文:
Send stdin keystrokes to channel without newline required
问题
我想在每次用户输入一个按键后,直接将按键发送到一个通道中。
我尝试了下面的代码,但是这并不能得到期望的结果,因为reader.ReadByte()
方法会阻塞,直到输入一个换行符为止。
func chars() <-chan byte {
ch := make(chan byte)
reader := bufio.NewReader(os.Stdin)
go func() {
for {
char, err := reader.ReadByte()
if err != nil {
log.Fatal(err)
}
ch <- char
}
}()
return ch
}
非常感谢任何关于如何让每个用户输入的字符立即进入通道的建议。
英文:
I'd like to send the user's keystrokes to a channel directly after each individual keystroke is made to stdin.
I've attempted the code below, but this doesn't give the desired result because the reader.ReadByte()
method blocks until newline is entered.
func chars() <-chan byte {
ch := make(chan byte)
reader := bufio.NewReader(os.Stdin)
go func() {
for {
char, err := reader.ReadByte()
if err != nil {
log.Fatal(err)
}
ch <- char
}
}()
return ch
}
Thank you for any advice on how might I get each user input character to go immediately to the channel without the need for a newline character.
答案1
得分: 10
标准输入默认是行缓冲的。这意味着它不会向您提供任何输入,直到遇到换行符为止。这不是Go特定的事情。
使其以非缓冲方式运行在不同平台上是高度特定的。正如Rami建议的,ncurses是一种方法。另一个选择是更轻量级的go-termbox包。
如果您想要完全手动操作(至少在Linux上),您可以查看为termios编写C绑定,或者直接在Go中进行系统调用。
关于Windows如何处理这个问题,我不清楚。您可以查看ncurses或termbox的源代码,看看它们是如何实现的。
英文:
Stdin is line-buffered by default. This means it will not yield any input to you, until a newline is encountered. This is not a Go specific thing.
Having it behave in a non-buffered way is highly platform specific. As Rami suggested, ncurses is a way to do it. Another option is the much lighter go-termbox package.
If you want to do it all manually (on Linux at least), you can look at writing C bindings for termios or do syscalls directly in Go.
How platforms like Windows handle this, I do not know. You can dig into the source code for ncurses or termbox to see how they did it.
答案2
得分: 5
如果你在Linux上,你可能想看一下Goncurses包
http://code.google.com/p/goncurses/
它有一个函数:GetChar(),这正是你想要的。
英文:
If you are on Linux, You might want to look at Goncurses package
http://code.google.com/p/goncurses/
It has the function: GetChar() which is what you want.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论