将标准输入的按键发送到通道,无需换行符。

huangapple go评论95阅读模式
英文:

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() &lt;-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 &lt;- 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.

huangapple
  • 本文由 发表于 2012年9月11日 07:00:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/12360597.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定