golang 学习笔记 使用cmd

package main

import (
	"bytes"
	"fmt"

	"os/exec"
)

func main() {
	cmd0 := exec.Command("go", "env")
	var outputBuf1 bytes.Buffer
	cmd0.Stdout = &outputBuf1
	if err := cmd0.Start(); err != nil {
		fmt.Printf("Error: The first command can not be startup %s\n", err)
		return
	}
	if err := cmd0.Wait(); err != nil {
		fmt.Printf("Error: Couldn't wait for the second command: %s\n", err)
		return
	}
	fmt.Printf("%s\n", outputBuf1.Bytes())

}

  

package main

import "fmt"
import "os/exec"

func main() {
        //create cmd
        cmd_go_env := exec.Command("go", "env")
        //cmd_grep:=exec.Command("grep","GOROOT")

        stdout_env, env_error := cmd_go_env.StdoutPipe()
        if env_error != nil {
                fmt.Println("Error happened about standard output pipe ", env_error)
                return
        }

        //env_error := cmd_go_env.Start()
        if env_error := cmd_go_env.Start(); env_error != nil {
                fmt.Println("Error happened in execution ", env_error)
                return
        }

        a1 := make([]byte, 1024)
        n, err := stdout_env.Read(a1)
        if err != nil {
                fmt.Println("Error happened in reading from stdout", err)
        }

        fmt.Printf("Standard output of go env command: %s", a1[:n])
}

  

猜你喜欢

转载自www.cnblogs.com/saryli/p/11642513.html
今日推荐