【问题标题】:Detect if a command is piped or not检测命令是否通过管道传输
【发布时间】:2017-10-12 08:12:39
【问题描述】:

有没有办法检测 go 中的命令是否通过管道传输?

例子:

cat test.txt | mygocommand #Piped, this is how it should be used
mygocommand # Not piped, this should be blocked

我正在阅读来自 Stdin reader := bufio.NewReader(os.Stdin)

【问题讨论】:

  • 为什么要阻止它?如果有人手动将输入输入到他们的终端,或者可能是复制粘贴或其他什么,这实际上是一个问题吗?
  • 也许你已经看过这个了,但是这里有一个对 shell 脚本的平行提问:stackoverflow.com/questions/911168/…
  • @user2357112 用户输入永远不会结束,因为不会有EOF,对吧?
  • @Florian: Ctrl-D 或 Ctrl-Z 在 Windows 的行首输入。

标签: go pipe


【解决方案1】:

您可以使用os.Stdin.Stat() 执行此操作。

package main

import (
  "fmt"
  "os"
)

func main() {
    fi, _ := os.Stdin.Stat()

    if (fi.Mode() & os.ModeCharDevice) == 0 {
        fmt.Println("data is from pipe")
    } else {
        fmt.Println("data is from terminal")
    }
}

(改编自https://www.socketloop.com/tutorials/golang-check-if-os-stdin-input-data-is-piped-or-from-terminal

【讨论】:

    猜你喜欢
    • 2016-10-27
    • 2018-08-18
    • 2012-09-08
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    • 1970-01-01
    • 2019-08-17
    • 1970-01-01
    相关资源
    最近更新 更多