You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
1.3 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package ShellUtil
import (
"bufio"
"bytes"
"errors"
"log"
"os/exec"
)
//
////封装一个函数来执行命令
//func ExecCommand(cmdLine string) {
// cmd := exec.Command("cmd.exe", "/c", cmdLine)
// err := cmd.Run()
//
// var out bytes.Buffer
// var stderr bytes.Buffer
// cmd.Stdout = &out
// cmd.Stderr = &stderr
// if err := cmd.Run(); err != nil {
// fmt.Println(fmt.Sprint(err) + ": " + stderr.String())
// }
// fmt.Println("Result: " + out.String())
//
// cmd.Wait()
// fmt.Printf("%s, error:%v \n", cmdLine, err)
//}
/**
功能带回显的执行DOS命令
作者:黄海
时间2020-05-18
*/
func Exec(name string, args ...string) error {
cmd := exec.Command(name, args...)
stderr, _ := cmd.StderrPipe()
stdout, _ := cmd.StdoutPipe()
if err := cmd.Start(); err != nil {
log.Println("exec the cmd ", name, " failed")
return err
}
// 正常日志
logScan := bufio.NewScanner(stdout)
go func() {
for logScan.Scan() {
log.Println(logScan.Text())
}
}()
// 错误日志
errBuf := bytes.NewBufferString("")
scan := bufio.NewScanner(stderr)
for scan.Scan() {
s := scan.Text()
log.Println("", s)
errBuf.WriteString(s)
errBuf.WriteString("\n")
}
// 等待命令执行完
cmd.Wait()
if !cmd.ProcessState.Success() {
// 执行失败,返回错误信息
return errors.New(errBuf.String())
}
return nil
}