以下工作并打印命令输出:
out, err := exec.Command("ps", "cax").Output()
Run Code Online (Sandbox Code Playgroud)
但是这个失败了(退出状态为1):
out, err := exec.Command("ps", "cax | grep myapp").Output()
Run Code Online (Sandbox Code Playgroud)
有什么建议?
Nad*_*adh 12
将所有内容传递给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))
}
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
out, err := exec.Command("bash", "-c", "ps cax | grep myapp").Output()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2718 次 |
| 最近记录: |