Read a character from standard input in Go (without pressing Enter)

前端 未结 6 1677
甜味超标
甜味超标 2020-12-08 20:29

I want to my app shows:

press any key to exit ...

And when I pressed any key, it exits.

How can I achieve this?

相关标签:
6条回答
  • 2020-12-08 20:41

    This is a minimal working example for those running a UNIX system:

    package main
    
    import (
        "fmt"
        "os"
        "os/exec"
    )
    
    func main() {
        // disable input buffering
        exec.Command("stty", "-F", "/dev/tty", "cbreak", "min", "1").Run()
        // do not display entered characters on the screen
        exec.Command("stty", "-F", "/dev/tty", "-echo").Run()
    
        var b []byte = make([]byte, 1)
        for {
            os.Stdin.Read(b)
            fmt.Println("I got the byte", b, "("+string(b)+")")
        }
    }
    
    0 讨论(0)
  • 2020-12-08 20:41

    Try this - http://play.golang.org/p/kg-QirlucY.

    Just read from the os.Stdin at the end of the func main

    0 讨论(0)
  • 2020-12-08 20:47

    termbox-go is a light-weight Go-native package which offers some rudimentary terminal control. Including the ability to get input in raw mode (read one character at a time without the default line-buffered behaviour).

    It also has fairly ok compatibility across different systems.

    And keyboard extends termbox-go to give some additional keyboard functionality like multi-key shortcuts and sequences.

    0 讨论(0)
  • 2020-12-08 20:47

    go-termbox is very heavyweight. It wants to take over the entire terminal window. For example, it clears the screen on startup, which may not be what you want.

    I put this together on OSX. Just a tiny getchar():

    https://github.com/paulrademacher/climenu/blob/master/getchar.go

    0 讨论(0)
  • 2020-12-08 20:54

    You can read a single key-press from a terminal in raw mode. Here is a package that should provide raw terminal mode to your program. Catch: it's Linux only.

    0 讨论(0)
  • 2020-12-08 20:58

    You could use this library (mine): https://github.com/eiannone/keyboard

    This is an example for getting a single keystroke:

    char, _, err := keyboard.GetSingleKey()
    if (err != nil) {
        panic(err)
    }
    fmt.Printf("You pressed: %q\r\n", char)
    
    0 讨论(0)
提交回复
热议问题