gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 00:37:55 24 4
gpt4 key购买 nike

所以我有:

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

但是 reader.ReadString('\n') 正在阻止执行。我想以非阻塞方式读取输入。是否可以使用 bufio 包或来自 Go 的任何其他标准库包从 os.Stdin 实现非阻塞缓冲输入?

最佳答案

一般来说,Go 中没有非阻塞 IO API 的概念。您可以使用 goroutines 完成同样的事情。

这是一个关于 Play 的例子, stdin 是模拟的,因为 play 不允许它。

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('\n')
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")
}

关于io - 如何使用 Go 以非阻塞方式从控制台读取输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27209697/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com