英文:
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())
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论