【问题标题】:Using golang's os/exec, how can I copy stdout from one process to stdin of another?使用 golang os/exec,如何将标准输出从一个进程复制到另一个进程的标准输入?
【发布时间】:2015-07-27 01:13:36
【问题描述】:

我想使用 go 的 os/exec module 模拟 bash 管道。这是 bash 中的一个虚拟示例:

$ ls | wc 
      42      48     807

如何在 Go 中模拟它?有没有办法用流来做到这一点?

【问题讨论】:

标签: go io stream


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2010-11-23
    • 2013-06-25
    • 2011-11-09
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多