github.com/orangebees/go-oneutils@v0.0.10/ExecCmd/func.go (about)

     1  package ExecCmd
     2  
     3  import (
     4  	"bytes"
     5  	"errors"
     6  	"os/exec"
     7  )
     8  
     9  // Run  运行命令
    10  func Run(dir string, name string, args ...string) error {
    11  	cmd := exec.Command(
    12  		name, args...)
    13  	cmd.Dir = dir
    14  	err := cmd.Start()
    15  	if err != nil {
    16  		return err
    17  	}
    18  	err = cmd.Wait()
    19  	if err != nil {
    20  		return err
    21  	}
    22  	return nil
    23  }
    24  
    25  // RunWithStdout 运行命令并取得成功返回值
    26  func RunWithStdout(dir string, name string, args ...string) (string, error) {
    27  	cmd := exec.Command(
    28  		name, args...)
    29  	cmd.Dir = dir
    30  	var stdout, stderr bytes.Buffer
    31  	cmd.Stdout = &stdout
    32  	cmd.Stderr = &stderr
    33  	err := cmd.Start()
    34  	if err != nil {
    35  		return "", err
    36  	}
    37  	err = cmd.Wait()
    38  	if err != nil {
    39  		return "", err
    40  	}
    41  	outStr, errStr := stdout.String(), stderr.String()
    42  	if err != nil {
    43  		return "", err
    44  	}
    45  	if errStr != "" {
    46  		return "", errors.New(errStr)
    47  	}
    48  	return outStr, nil
    49  }