golang执行指令并获取输出

golang执行指令并获取输出

代码

package main

import (
    "os/exec"
    "io/ioutil"
    "fmt"
)

type Output struct{
    Stdoutput string ;
    Stderrput string ;
}

// 执行命令
func exec_cmd(cmd *exec.Cmd) (Output, error) {
    // 创建标准输出管道
    stdoutPipe, _ := cmd.StdoutPipe()
    // 创建错误输出管道
    stderrPipe, _ := cmd.StderrPipe()

    cmd.Start()

    // 获取两个管道的数据
    stdoutBytes, _ := ioutil.ReadAll(stdoutPipe)
    stderrBytes, _ := ioutil.ReadAll(stderrPipe)

    // 关闭管道
    stdoutPipe.Close()
    stderrPipe.Close()

    // 等待执行结束
    err := cmd.Wait()

    // 获取两个管道里的数据
    var output Output
    output.Stdoutput = string(stdoutBytes)
    output.Stderrput = string(stderrBytes)

    return output, err
}

// test
func main() {
    cmd := exec.Command("ls", "-lh")
    output, err := exec_cmd(cmd)
    fmt.Printf("stdout: [%s]\nstderr: [%s]\n[%v]", output.Stdoutput, output.Stderrput, err) 
}

测试

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注