Determine if Stdin has data with Go

后端 未结 2 980
北海茫月
北海茫月 2021-01-12 07:38

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

The post Read from initial stdin in GO? shows how to read the data, but unfortunately b

2条回答
  •  既然无缘
    2021-01-12 08:27

    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

    package main
    
    import (
      "os"
      "fmt"
    )
    
    func main() {
      fi, err := os.Stdin.Stat()
      if err != nil {
        panic(err)
      }
      if fi.Mode() & os.ModeNamedPipe == 0 {
        fmt.Println("no pipe :(")
      } else {
        fmt.Println("hi pipe!")
      }
    }
    

提交回复
热议问题