【问题标题】:Go exec.Command() - run command which contains pipeGo exec.Command() - 运行包含管道的命令
【发布时间】:2017-04-23 14:25:45
【问题描述】:

以下工作并打印命令输出:

out, err := exec.Command("ps", "cax").Output()

但是这个失败(退出状态为 1):

out, err := exec.Command("ps", "cax | grep myapp").Output()

有什么建议吗?

【问题讨论】:

    标签: go pipe exec


    【解决方案1】:

    将所有内容传递给 bash 可以,但这是一种更惯用的方式。

    package main
    
    import (
        "fmt"
        "os/exec"
    )
    
    func main() {
        grep := exec.Command("grep", "redis")
        ps := exec.Command("ps", "cax")
    
        // Get ps's stdout and attach it to grep's stdin.
        pipe, _ := ps.StdoutPipe()
        defer pipe.Close()
    
        grep.Stdin = pipe
    
        // Run ps first.
        ps.Start()
    
        // Run and get the output of grep.
        res, _ := grep.Output()
    
        fmt.Println(string(res))
    }
    

    【讨论】:

      【解决方案2】:

      你可以这样做:

      out, err := exec.Command("bash", "-c", "ps cax | grep myapp").Output()
      

      【讨论】:

        【解决方案3】:

        在这种特定情况下,您实际上并不需要管道,Go 也可以grep

        package main
        
        import (
           "bufio"
           "bytes"
           "os/exec"
           "strings"
        )
        
        func main() {
           c, b := exec.Command("go", "env"), new(bytes.Buffer)
           c.Stdout = b
           c.Run()
           s := bufio.NewScanner(b)
           for s.Scan() {
              if strings.Contains(s.Text(), "CACHE") {
                 println(s.Text())
              }
           }
        }
        

        【讨论】:

          猜你喜欢
          • 2011-11-13
          • 1970-01-01
          • 2016-09-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多