Go exec.Command() – 运行包含管道的命令

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

Go exec.Command() - run command which contains pipe

问题

以下是要翻译的内容:

以下代码可以执行并打印命令输出:

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

但是以下代码执行失败(退出状态为1):

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

有什么建议吗?

英文:

The following works and prints the command output:

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

but this one fails (with exit status 1):

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

Any suggestions?

答案1

得分: 27

将所有内容传递给bash可以工作,但这里有一种更符合惯用方式的方法。

package main

import (
	"fmt"
	"os/exec"
)

func main() {
	grep := exec.Command("grep", "redis")
	ps := exec.Command("ps", "cax")

	// 获取ps的标准输出并将其连接到grep的标准输入。
	pipe, _ := ps.StdoutPipe()
	defer pipe.Close()

	grep.Stdin = pipe

	// 先运行ps。
	ps.Start()

	// 运行并获取grep的输出。
	res, _ := grep.Output()

	fmt.Println(string(res))
}
英文:

Passing everything to bash works, but here's a more idiomatic way of doing it.

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

得分: 18

你可以这样做:

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

You could do:

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

答案3

得分: 2

在这种特定情况下,你实际上不需要使用管道,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())
      }
   }
}
英文:

In this specific case, you don't really need a pipe, a Go can grep as well:

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

huangapple
  • 本文由 发表于 2016年12月8日 19:02:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/41037870.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定