确定Go中Stdin是否有数据

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

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就像任何其他的“文件”,所以你可以检查它的大小:

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")
	}
}

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

$ ./pipe
Stdin is empty
$ echo test | ./pipe
5 bytes available in 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

答案2

得分: 8

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

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("没有管道 :(")
  } else {
    fmt.Println("有管道!")
  }
}

你可以在这个链接中找到更多关于这个解决方案的信息: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

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!")
  }
}

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:

确定