在Golang中检查STDIN上是否有要阅读的内容 [英] Check if there is something to read on STDIN in Golang

查看:290
本文介绍了在Golang中检查STDIN上是否有要阅读的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个命令行实用程序来表现不同的行为,如果一些字符串被传送到它的STDIN。这里有一个简单的例子:

I need a command line utility to behave different if some string is piped into its STDIN. Here's some minimal example:

package main // file test.go

import (
    "fmt"
    "io/ioutil"
    "os"
)

func main() {
    bytes, _ := ioutil.ReadAll(os.Stdin)

    if len(bytes) > 0 {
        fmt.Println("Something on STDIN: " + string(bytes))
    } else {
        fmt.Println("Nothing on STDIN")
    }
}

如果你像这样调用它,它可以正常工作:

This works fine if you call it like that:

echo foo | go run test.go

如果 test.go 在STDIN上没有任何东西被调用,这个东西就在... ...

If test.go is called without anything on STDIN, the thing stucks at...

bytes, _ := ioutil.ReadAll(os.Stdin)

...等待 EOF

我需要做些什么才能做到这一点?

What do I need to do to get this going?

预先感谢!

推荐答案

我使用os.ModeCharDevice解决了这个问题:

I solved this by using os.ModeCharDevice:

stat, _ := os.Stdin.Stat()
if (stat.Mode() & os.ModeCharDevice) == 0 {
    fmt.Println("data is being piped to stdin")
} else {
    fmt.Println("stdin is from a terminal")
}

这篇关于在Golang中检查STDIN上是否有要阅读的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆