确定Go中Stdin是否有数据

huangapple go评论130阅读模式
英文:

Determine if Stdin has data with Go

问题

有没有办法检查输入流(os.Stdin)是否有数据?

这篇帖子https://stackoverflow.com/questions/12363030/read-from-initial-stdin-in-go/12384207展示了如何读取数据,但是如果没有数据输入到stdin中,它会阻塞。

英文:

Is there a way to check if the input stream (os.Stdin) has data?

The post https://stackoverflow.com/questions/12363030/read-from-initial-stdin-in-go/12384207 shows how to read the data, but unfortunately blocks if no data is piped into the stdin.

答案1

得分: 16

os.Stdin就像任何其他的“文件”,所以你可以检查它的大小:

  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. )
  6. func main() {
  7. file := os.Stdin
  8. fi, err := file.Stat()
  9. if err != nil {
  10. fmt.Println("file.Stat()", err)
  11. }
  12. size := fi.Size()
  13. if size > 0 {
  14. fmt.Printf("%v bytes available in Stdin\n", size)
  15. } else {
  16. fmt.Println("Stdin is empty")
  17. }
  18. }

我将其构建为一个“管道”可执行文件,以下是它的工作原理:

  1. $ ./pipe
  2. Stdin is empty
  3. $ echo test | ./pipe
  4. 5 bytes available in Stdin
英文:

os.Stdin is like any other "file", so you can check it's size:

  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. )
  6. func main() {
  7. file := os.Stdin
  8. fi, err := file.Stat()
  9. if err != nil {
  10. fmt.Println("file.Stat()", err)
  11. }
  12. size := fi.Size()
  13. if size > 0 {
  14. fmt.Printf("%v bytes available in Stdin\n", size)
  15. } else {
  16. fmt.Println("Stdin is empty")
  17. }
  18. }

I built this as a "pipe" executable, here is how it works:

  1. $ ./pipe
  2. Stdin is empty
  3. $ echo test | ./pipe
  4. 5 bytes available in Stdin

答案2

得分: 8

这似乎是一个可靠的解决方案,即使通过管道传递了延迟的数据,也可以正常工作。

  1. package main
  2. import (
  3. "os"
  4. "fmt"
  5. )
  6. func main() {
  7. fi, err := os.Stdin.Stat()
  8. if err != nil {
  9. panic(err)
  10. }
  11. if fi.Mode() & os.ModeNamedPipe == 0 {
  12. fmt.Println("没有管道 :(")
  13. } else {
  14. fmt.Println("有管道!")
  15. }
  16. }

你可以在这个链接中找到更多关于这个解决方案的信息:https://coderwall.com/p/zyxyeg/golang-having-fun-with-os-stdin-and-shell-pipes

英文:

This seems to be reliable solution and works even with sleep/delayed data via pipe.
https://coderwall.com/p/zyxyeg/golang-having-fun-with-os-stdin-and-shell-pipes

  1. package main
  2. import (
  3. "os"
  4. "fmt"
  5. )
  6. func main() {
  7. fi, err := os.Stdin.Stat()
  8. if err != nil {
  9. panic(err)
  10. }
  11. if fi.Mode() & os.ModeNamedPipe == 0 {
  12. fmt.Println("no pipe :(")
  13. } else {
  14. fmt.Println("hi pipe!")
  15. }
  16. }

huangapple
  • 本文由 发表于 2014年3月22日 00:00:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/22563616.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定