猿问

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

所以我有:


import (

    "bufio"

    "os"

)

//...

var reader = bufio.NewReader(os.Stdin)

str, err := reader.ReadString('\n')

但是reader.ReadString('\n')正在阻止执行。我想以非阻塞方式读取输入。是否可以通过os.Stdin使用bufioGo 中的包或任何其他 std lib 包来实现非阻塞缓冲输入?


烙印99
浏览 269回答 1
1回答

慕村9548890

一般来说,Go 中没有非阻塞 IO API 的概念。你可以通过使用 goroutines 来完成同样的事情。这是一个关于Play的例子, stdin 是模拟的,因为 play 不允许它。package mainimport "fmt"import "time"func main() {&nbsp; &nbsp; ch := make(chan string)&nbsp; &nbsp; go func(ch chan string) {&nbsp; &nbsp; &nbsp; &nbsp; /* Uncomment this block to actually read from stdin&nbsp; &nbsp; &nbsp; &nbsp; reader := bufio.NewReader(os.Stdin)&nbsp; &nbsp; &nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; s, err := reader.ReadString('\n')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if err != nil { // Maybe log non io.EOF errors, if you want&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; close(ch)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ch <- s&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; */&nbsp; &nbsp; &nbsp; &nbsp; // Simulating stdin&nbsp; &nbsp; &nbsp; &nbsp; ch <- "A line of text"&nbsp; &nbsp; &nbsp; &nbsp; close(ch)&nbsp; &nbsp; }(ch)stdinloop:&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; select {&nbsp; &nbsp; &nbsp; &nbsp; case stdin, ok := <-ch:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if !ok {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break stdinloop&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Read input from stdin:", stdin)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; case <-time.After(1 * time.Second):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Do something when there is nothing read from stdin&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println("Done, stdin must be closed")}
随时随地看视频慕课网APP

相关分类

Go
我要回答