【问题标题】:function similar to getchar类似于 getchar 的功能
【发布时间】:2012-12-15 04:12:57
【问题描述】:

是否有类似于 C 的 getchar 的 Go 函数能够处理控制台中的制表符?我想在我的控制台应用程序中完成某种完成。

【问题讨论】:

标签: console go getchar


【解决方案1】:

这里的其他答案建议如下:

  • 使用 cgo

  • os.Exec 的stty

    • 不便携
    • 效率低下
    • 容易出错
  • 使用使用/dev/tty的代码

    • 不便携
  • 使用 GNU readline 包

    • 如果它是 C readline 的包装器或使用上述技术之一实现,则效率低下
    • 否则没关系

但是,对于简单的情况,这很容易,只需使用来自 Go Project's Sub-repositories 的包。

基本上,使用 terminal.MakeRaw 和 terminal.Restore 将标准输入设置为原始模式(检查错误,例如,如果 stdin 不是终端);那么您可以直接从os.Stdin 读取字节,或者更有可能通过bufio.Reader 读取字节(以提高效率)。

例如,像这样的:

package main

import (
    "bufio"
    "fmt"
    "log"
    "os"

    "golang.org/x/crypto/ssh/terminal"
)

func main() {
    // fd 0 is stdin
    state, err := terminal.MakeRaw(0)
    if err != nil {
        log.Fatalln("setting stdin to raw:", err)
    }
    defer func() {
        if err := terminal.Restore(0, state); err != nil {
            log.Println("warning, failed to restore terminal:", err)
        }
    }()

    in := bufio.NewReader(os.Stdin)
    for {
        r, _, err := in.ReadRune()
        if err != nil {
            log.Println("stdin:", err)
            break
        }
        fmt.Printf("read rune %q\r\n", r)
        if r == 'q' {
            break
        }
    }
}

【讨论】:

  • 这对我来说效果很好。我只需要将"fmt" 添加到import。
  • @RikRenich opps,经过测试,我将最终的log 更改为fmt,但没有调整导入。现已修复。
【解决方案2】:

您也可以使用 ReadRune:

reader := bufio.NewReader(os.Stdin)
// ...
char, _, err := reader.ReadRune()
if err != nil {
    fmt.Println("Error reading key...", err)
}

符文类似于字符,因为GoLang并没有真正的字符,为了尝试和支持多种语言/unicode/等。

【讨论】:

  • ReadRune 一次读取一个字符,但只有在控制台中按回车时才会触发;这就是为什么这不能解决 OP 的问题。 (我想知道为什么你没有更多的赞成票,只是试了一下:))
【解决方案3】:

1- 你可以使用C.getch():

这适用于 Windows 命令行,无需 Enter 仅读取一个字符:
(在 shell(终端)内运行输出二进制文件,而不是在管道或编辑器内。)

package main

//#include<conio.h>
import "C"

import "fmt"

func main() {
    c := C.getch()
    fmt.Println(c)
}

2- 对于 Linux(在 Ubuntu 上测试):

package main

/*
#include <stdio.h>
#include <unistd.h>
#include <termios.h>
char getch(){
    char ch = 0;
    struct termios old = {0};
    fflush(stdout);
    if( tcgetattr(0, &old) < 0 ) perror("tcsetattr()");
    old.c_lflag &= ~ICANON;
    old.c_lflag &= ~ECHO;
    old.c_cc[VMIN] = 1;
    old.c_cc[VTIME] = 0;
    if( tcsetattr(0, TCSANOW, &old) < 0 ) perror("tcsetattr ICANON");
    if( read(0, &ch,1) < 0 ) perror("read()");
    old.c_lflag |= ICANON;
    old.c_lflag |= ECHO;
    if(tcsetattr(0, TCSADRAIN, &old) < 0) perror("tcsetattr ~ICANON");
    return ch;
}
*/
import "C"

import "fmt"

func main() {
    fmt.Println(C.getch())
    fmt.Println()
}

见:
What is Equivalent to getch() & getche() in Linux?
Why can't I find <conio.h> on Linux?


3- 这也有效,但需要“输入”:

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    r := bufio.NewReader(os.Stdin)
    c, err := r.ReadByte()
    if err != nil {
        panic(err)
    }
    fmt.Println(c)
}

【讨论】:

  • 仍然需要在 openSUSE Leap 42.1 上为我按 Enter 键。 :(
  • 对不起,我忘了提到conio.h 仅适用于 Windows!我试过this 和this,它可以运行但是getch() 总是返回-1。
  • 最后,我采用@blinry 的方法。
  • @lfree:请参阅 Linux 的新编辑 (2),希望对您有所帮助。
  • 第二种方法适用于 openSUSE Leap42.1。非常感谢! :)
【解决方案4】:

C 的getchar() 示例:

#include <stdio.h>
void main()
{
    char ch;
    ch = getchar();
    printf("Input Char Is :%c",ch);
}

Go 等价物:

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {

    reader := bufio.NewReader(os.Stdin)
    input, _ := reader.ReadString('\n')

    fmt.Printf("Input Char Is : %v", string([]byte(input)[0]))

    // fmt.Printf("You entered: %v", []byte(input))
}

最后一个注释行显示当您按下tab 时,第一个元素是 U+0009('CHARACTER TABULATION')。

但是根据您的需要(检测选项卡)C 的getchar() 不适合,因为它需要用户按回车键。你需要的是像@miku 提到的 ncurses 的 getch()/readline/jLine 之类的东西。有了这些,您实际上会等待一次击键。

所以你有多种选择:

  1. 使用ncurses / readline 绑定,例如https://code.google.com/p/goncurses/ 或类似https://github.com/nsf/termbox 的等效项

  2. 滚动您自己的起点,请参阅http://play.golang.org/p/plwBIIYiqG

  3. 使用os.Exec 运行stty 或jLine。

参考:

https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/zhBE5MH4n-Q

https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/S9AO_kHktiY

https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/icMfYF8wJCk

【讨论】:

    【解决方案5】:

    感谢 Paul Rademacher - 这很有效(至少在 Mac 上):

    package main
    
    import (
        "bytes"
        "fmt"
    
        "github.com/pkg/term"
    )
    
    func getch() []byte {
        t, _ := term.Open("/dev/tty")
        term.RawMode(t)
        bytes := make([]byte, 3)
        numRead, err := t.Read(bytes)
        t.Restore()
        t.Close()
        if err != nil {
            return nil
        }
        return bytes[0:numRead]
    }
    
    func main() {
        for {
            c := getch()
            switch {
            case bytes.Equal(c, []byte{3}):
                return
            case bytes.Equal(c, []byte{27, 91, 68}): // left
                fmt.Println("LEFT pressed")
            default:
                fmt.Println("Unknown pressed", c)
            }
        }
        return
    }
    

    【讨论】:

    • 在 Linux 上也能完美运行
    • 使用/dev/tty 是不可移植的。 从不忽略错误!不要为每个“字符”翻转终端进入/退出原始模式,不要为每个“字符”重新打开“/dev/tty”。这实际上并没有得到字符,而是最多三个字节。
    【解决方案6】:

    假设您想要无缓冲的输入(无需按回车键),这可以在 UNIX 系统上完成:

    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)+")")
        }
    }
    

    【讨论】:

    • 这会使终端在退出后处于非回显状态。添加defer exec.Command("stty", "-F", "/dev/tty", "echo") 可以解决这个问题。
    • defer exec.Command("stty", "-F", "/dev/tty", "echo").Run() 对我不起作用,我必须输入 'reset ' :(
    • 当您可以只使用来自golang.org/x/crypto/ssh/terminal 的terminal.MakeRaw 时,不要执行大量低效、容易出错、不可移植等 stty。
    • 如果延迟“不起作用”,实际构建并编译项目以运行它,而不是执行 go run *.go。这对我有用。
    猜你喜欢
    • 2012-10-04
    • 2012-12-19
    • 2017-05-21
    • 1970-01-01
    • 2014-10-04
    • 2019-03-31
    • 2015-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多