如何在 Go 中通过管道传输多个命令? [英] How to pipe several commands in Go?

查看:30
本文介绍了如何在 Go 中通过管道传输多个命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Go 中通过管道将多个外部命令连接在一起?我已经尝试过这段代码,但我收到一个错误消息,指出 exit status 1.

How can I pipe several external commands together in Go? I've tried this code but I get an error that says exit status 1.

package main

import (
    "io"
    "log"
    "os"
    "os/exec"
)

func main() {
    c1 := exec.Command("ls")
    stdout1, err := c1.StdoutPipe()
    if err != nil {
        log.Fatal(err)
    }

    if err = c1.Start(); err != nil {
        log.Fatal(err)
    }
    if err = c1.Wait(); err != nil {
        log.Fatal(err)
    }

    c2 := exec.Command("wc", "-l")
    c2.Stdin = stdout1

    stdout2, err := c2.StdoutPipe()
    if err != nil {
        log.Fatal(err)
    }

    if err = c2.Start(); err != nil {
        log.Fatal(err)
    }
    if err = c2.Wait(); err != nil {
        log.Fatal(err)
    }

    io.Copy(os.Stdout, stdout2)
}

推荐答案

StdoutPipe 返回一个管道,该管道将连接到命令的命令启动时的标准输出.管道将被关闭Wait 看到命令退出后自动执行.

StdoutPipe returns a pipe that will be connected to the command's standard output when the command starts. The pipe will be closed automatically after Wait sees the command exit.

(来自 http://golang.org/pkg/os/exec/#Cmd.StdinPipe )

您执行 c1.Wait 的事实会关闭 stdoutPipe.

The fact you do c1.Wait closes the stdoutPipe.

我做了一个工作示例(只是一个演示,添加错误捕获!):

I made a working example (just a demo, add error catching!) :

package main

import (
    "bytes"
    "io"
    "os"
    "os/exec"
)

func main() {
    c1 := exec.Command("ls")
    c2 := exec.Command("wc", "-l")

    r, w := io.Pipe() 
    c1.Stdout = w
    c2.Stdin = r

    var b2 bytes.Buffer
    c2.Stdout = &b2

    c1.Start()
    c2.Start()
    c1.Wait()
    w.Close()
    c2.Wait()
    io.Copy(os.Stdout, &b2)
}

这篇关于如何在 Go 中通过管道传输多个命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆