Go – Pipe 3 or more commands with os.exec()?

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

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

https://stackoverflow.com/a/10953142/3761308

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

huangapple
  • 本文由 发表于 2016年12月28日 20:13:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/41361929.html
匿名

发表评论

匿名网友

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

确定