英文:
Go - Pipe 3 or more commands with os.exec()?
问题
你可以使用Go语言中的io.Pipe()
函数来实现管道连接多个命令。下面是一个示例代码:
package main
import (
"fmt"
"io"
"os"
"os/exec"
)
func main() {
cmd1 := exec.Command("ls")
cmd2 := exec.Command("grep", "example")
cmd3 := exec.Command("wc", "-l")
// 创建管道
pipeReader, pipeWriter := io.Pipe()
// 将cmd1的输出连接到pipeWriter
cmd1.Stdout = pipeWriter
// 将cmd2的输入连接到pipeReader
cmd2.Stdin = pipeReader
// 将cmd2的输出连接到os.Stdout
cmd2.Stdout = os.Stdout
// 将cmd3的输入连接到cmd2的输出
cmd3.Stdin = cmd2.Stdout
// 启动命令
cmd1.Start()
cmd2.Start()
cmd3.Start()
// 等待命令执行完成
cmd1.Wait()
pipeWriter.Close()
cmd2.Wait()
cmd3.Wait()
}
这段代码将会执行ls | grep example | wc -l
的命令,并将结果输出到标准输出。你可以根据需要修改命令和参数。
英文:
How can I pipe 3+ commands together in Go (for example ls | grep | wc)? I've tried to modify this code that is for piping 2 commands, but can't figure out the correct way.,
package main
import (
"os"
"os/exec"
)
func main() {
c1 := exec.Command("ls")
c2 := exec.Command("wc", "-l")
c2.Stdin, _ = c1.StdoutPipe()
c2.Stdout = os.Stdout
_ = c2.Start()
_ = c1.Run()
_ = c2.Wait()
}
答案1
得分: 4
package main
import (
"os"
"os/exec"
)
func main() {
c1 := exec.Command("ls")
c2 := exec.Command("grep", "-i", "o")
c3 := exec.Command("wc", "-l")
c2.Stdin, _ = c1.StdoutPipe()
c3.Stdin, _ = c2.StdoutPipe()
c3.Stdout = os.Stdout
_ = c3.Start()
_ = c2.Start()
_ = c1.Run()
_ = c2.Wait()
_ = c3.Wait()
}
这是一个Go语言的代码片段,它使用了os/exec
包来执行一系列命令。代码的功能是执行ls
命令,然后将输出传递给grep -i o
命令,再将输出传递给wc -l
命令。最后,将结果输出到标准输出。
英文:
package main
import (
"os"
"os/exec"
)
func main() {
c1 := exec.Command("ls")
c2 := exec.Command("grep", "-i", "o")
c3 := exec.Command("wc", "-l")
c2.Stdin, _ = c1.StdoutPipe()
c3.Stdin, _ = c2.StdoutPipe()
c3.Stdout = os.Stdout
_ = c3.Start()
_ = c2.Start()
_ = c1.Run()
_ = c2.Wait()
_ = c3.Wait()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论