52 lines
1016 B
Go
52 lines
1016 B
Go
package utils
|
|
|
|
import (
|
|
"bufio"
|
|
"context"
|
|
"io"
|
|
"os/exec"
|
|
"strings"
|
|
"syscall"
|
|
)
|
|
|
|
type execUtils struct{}
|
|
|
|
var Exec = &execUtils{}
|
|
|
|
func (e *execUtils) Command(cmdstr, dir string) (string, error) {
|
|
reader, err := e.CommandContext(context.Background(), cmdstr, dir, nil)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
scanner := bufio.NewScanner(reader)
|
|
var out string
|
|
for scanner.Scan() {
|
|
out += scanner.Text() + "\n"
|
|
}
|
|
return out, reader.Close()
|
|
}
|
|
|
|
func (e *execUtils) CommandContext(ctx context.Context, cmdstr, dir string, cancel func()) (io.ReadCloser, error) {
|
|
cmdArgs := strings.Split(cmdstr, " ")
|
|
cmd := exec.CommandContext(ctx, cmdArgs[0], cmdArgs[1:]...)
|
|
cmd.Dir = dir
|
|
cmd.Cancel = func() error {
|
|
if cancel != nil {
|
|
cancel()
|
|
}
|
|
return cmd.Process.Kill()
|
|
}
|
|
// 关闭黑框
|
|
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
|
|
// 输出
|
|
stdout, err := cmd.StdoutPipe()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
err = cmd.Start()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return stdout, nil
|
|
}
|