使用golang的os/exec,我如何将一个进程的stdout复制到另一个进程的stdin?

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

Using golang's os/exec, how can I copy stdout from one process to stdin of another?

问题

我想使用Go的os/exec模块来模拟一个bash管道。以下是一个在bash中的示例:

$ ls | wc 
      42      48     807

我该如何在Go中模拟这个过程?是否有一种方法可以使用流来实现?

英文:

I want to emulate a bash pipe using go's os/exec module. Here's a dummy example in bash:

$ ls | wc 
      42      48     807

How can I emulate that in Go? Is there a way to do it with streams?

答案1

得分: 2

通过Brad Fitzpatrick的方式,这是一种实现方法。你可以将第二个命令的Stdin属性重新分配给第一个命令的stdout写入器。

ls := exec.Command("ls")
wc := exec.Command("wc")
lsOut, _ := ls.StdoutPipe()
ls.Start()
wc.Stdin = lsOut

o, _ := wc.Output()
fmt.Println(string(o))
英文:

Via Brad Fitzpatrick, here's one way to do it. You can reassign the Stdin property of the second command to the stdout writer from the first command.

    ls := exec.Command("ls")
    wc := exec.Command("wc")
    lsOut, _ := ls.StdoutPipe()
    ls.Start()
    wc.Stdin = lsOut

    o, _ := wc.Output()
    fmt.Println(string(o))

huangapple
  • 本文由 发表于 2015年7月27日 09:13:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/31643678.html
匿名

发表评论

匿名网友

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

确定