dpf56454 2014-11-30 03:30
浏览 422
已采纳

如何使用Go以非阻塞方式从控制台读取输入?

So I have:

import (
    "bufio"
    "os"
)
//...
var reader = bufio.NewReader(os.Stdin)
str, err := reader.ReadString('
')

But reader.ReadString(' ') is blocking execution. I would like to read input in a non blocking way. Is it possible to achieve non blocking buffered input from os.Stdin using bufio package or any other std lib package from Go?

  • 写回答

1条回答 默认 最新

  • douweng1935 2014-11-30 04:31
    关注

    In general there isn't a concept of non-blocking IO APIs in Go. You accomplish the same thing by using goroutines.

    Here's an example on Play, stdin is simulated since play doesn't allow for it.

    package main
    
    import "fmt"
    import "time"
    
    func main() {
        ch := make(chan string)
        go func(ch chan string) {
            /* Uncomment this block to actually read from stdin
            reader := bufio.NewReader(os.Stdin)
            for {
                s, err := reader.ReadString('
    ')
                if err != nil { // Maybe log non io.EOF errors, if you want
                    close(ch)
                    return
                }
                ch <- s
            }
            */
            // Simulating stdin
            ch <- "A line of text"
            close(ch)
        }(ch)
    
    stdinloop:
        for {
            select {
            case stdin, ok := <-ch:
                if !ok {
                    break stdinloop
                } else {
                    fmt.Println("Read input from stdin:", stdin)
                }
            case <-time.After(1 * time.Second):
                // Do something when there is nothing read from stdin
            }
        }
        fmt.Println("Done, stdin must be closed")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置