function similar to getchar

前端 未结 6 666
终归单人心
终归单人心 2020-12-04 19:18

Is there a Go function similar to C\'s getchar able to handle tab press in console? I want to make some sort of completion in my console app.

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 19:55

    Assuming that you want unbuffered input (without having to hit enter), this does the job on UNIX systems:

    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()
        // restore the echoing state when exiting
        defer 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)+")")
        }
    }
    

提交回复
热议问题