使用Go确定Stdin是否具有数据 [英] Determine if Stdin has data with Go
本文介绍了使用Go确定Stdin是否具有数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以检查输入流(os.Stdin
)是否有数据?
Is there a way to check if the input stream (os.Stdin
) has data?
帖子从GO中的初始stdin中读取内容?显示了如何读取数据,但不幸的是,如果没有数据输入标准输入,则会阻塞.
The post Read from initial stdin in GO? shows how to read the data, but unfortunately blocks if no data is piped into the stdin.
推荐答案
os.Stdin与其他任何文件"一样,因此您可以检查其大小:
os.Stdin is like any other "file", so you can check it's size:
package main
import (
"fmt"
"os"
)
func main() {
file := os.Stdin
fi, err := file.Stat()
if err != nil {
fmt.Println("file.Stat()", err)
}
size := fi.Size()
if size > 0 {
fmt.Printf("%v bytes available in Stdin\n", size)
} else {
fmt.Println("Stdin is empty")
}
}
我将其构建为管道"可执行文件,其工作方式如下:
I built this as a "pipe" executable, here is how it works:
$ ./pipe
Stdin is empty
$ echo test | ./pipe
5 bytes available in Stdin
这篇关于使用Go确定Stdin是否具有数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文