拓展类型 自定义工具类型
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user