【发布时间】:2015-07-27 01:13:36
【问题描述】:
我想使用 go 的 os/exec module 模拟 bash 管道。这是 bash 中的一个虚拟示例:
$ ls | wc
42 48 807
如何在 Go 中模拟它?有没有办法用流来做到这一点?
【问题讨论】:
-
How to pipe several commands? 的完全相同的副本
我想使用 go 的 os/exec module 模拟 bash 管道。这是 bash 中的一个虚拟示例:
$ ls | wc
42 48 807
如何在 Go 中模拟它?有没有办法用流来做到这一点?
【问题讨论】:
Via Brad Fitzpatrick, here's one way to do it。您可以将第二个命令的 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))
【讨论】: