gpt4 book ai didi

go - 如何使用 Stdin 获取输入并等待 Golang 的 Stdin 中有新数据

转载 作者:数据小太阳 更新时间:2023-10-29 03:24:04 28 4
gpt4 key购买 nike

我有一段代码需要在每次 Stdin 中有新输入时执行,但如果 Stdin 中没有任何内容,程序不应该终止,而是应该等待 Stdin 中的新数据,然后运行计算代码那个数据。

这在 Golang 中如何实现?下面是一段代码:

 stat, _ := os.Stdin.Stat()
if (stat.Mode() & os.ModeCharDevice) == 0 {
fmt.Println("data is being piped to stdin")
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
text:= scanner.Text()
fmt.Println(text)
// do some computation ....

} else {
fmt.Println("No data in stdin")
// wait until there is new data in Stdin
}

谁能帮我想办法实现这一目标。

最佳答案

您可以将您的 Scan 调用包装在一个循环中:

for text := ""; text != ""; {
for scanner.Scan() {
text = scanner.Text()
// ...
}
}

即使用户输入为空,这也会产生循环的副作用。

关于go - 如何使用 Stdin 获取输入并等待 Golang 的 Stdin 中有新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46957892/

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