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

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

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

问题

以下是要翻译的内容:

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

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

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

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

有什么建议吗?

英文:

The following works and prints the command output:

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

but this one fails (with exit status 1):

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

Any suggestions?

答案1

得分: 27

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

  1. package main
  2. import (
  3. "fmt"
  4. "os/exec"
  5. )
  6. func main() {
  7. grep := exec.Command("grep", "redis")
  8. ps := exec.Command("ps", "cax")
  9. // 获取ps的标准输出并将其连接到grep的标准输入。
  10. pipe, _ := ps.StdoutPipe()
  11. defer pipe.Close()
  12. grep.Stdin = pipe
  13. // 先运行ps。
  14. ps.Start()
  15. // 运行并获取grep的输出。
  16. res, _ := grep.Output()
  17. fmt.Println(string(res))
  18. }
英文:

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

  1. package main
  2. import (
  3. "fmt"
  4. "os/exec"
  5. )
  6. func main() {
  7. grep := exec.Command("grep", "redis")
  8. ps := exec.Command("ps", "cax")
  9. // Get ps's stdout and attach it to grep's stdin.
  10. pipe, _ := ps.StdoutPipe()
  11. defer pipe.Close()
  12. grep.Stdin = pipe
  13. // Run ps first.
  14. ps.Start()
  15. // Run and get the output of grep.
  16. res, _ := grep.Output()
  17. fmt.Println(string(res))
  18. }

答案2

得分: 18

你可以这样做:

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

You could do:

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

答案3

得分: 2

在这种特定情况下,你实际上不需要使用管道,Go语言也可以使用grep

  1. package main
  2. import (
  3. "bufio"
  4. "bytes"
  5. "os/exec"
  6. "strings"
  7. )
  8. func main() {
  9. c, b := exec.Command("go", "env"), new(bytes.Buffer)
  10. c.Stdout = b
  11. c.Run()
  12. s := bufio.NewScanner(b)
  13. for s.Scan() {
  14. if strings.Contains(s.Text(), "CACHE") {
  15. println(s.Text())
  16. }
  17. }
  18. }
英文:

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

  1. package main
  2. import (
  3. "bufio"
  4. "bytes"
  5. "os/exec"
  6. "strings"
  7. )
  8. func main() {
  9. c, b := exec.Command("go", "env"), new(bytes.Buffer)
  10. c.Stdout = b
  11. c.Run()
  12. s := bufio.NewScanner(b)
  13. for s.Scan() {
  14. if strings.Contains(s.Text(), "CACHE") {
  15. println(s.Text())
  16. }
  17. }
  18. }

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:

确定