[go]os/exec执行shell命令

时间:2023-03-10 07:04:03
[go]os/exec执行shell命令
// exec基础使用

import (
"os/exec"
) cmd = exec.Command("C:\\cygwin64\\bin\\bash.exe", "-c", "echo 1")
err = cmd.Run()
// 捕获输出

cmd = exec.Command("C:\\cygwin64\\bin\\bash.exe", "-c", "/usr/bin/python xxx.py")
output, err = cmd.CombinedOutput() // 执行了命令, 捕获了子进程的输出(pipe)
fmt.Println(string(output))
// 1s超时后,kill程序(强制终止/超时终止)

func main() {
// 执行1个cmd, 让它在一个协程里去执行, 让它执行2秒: sleep 2; echo hello;
// 1秒的时候, 我们杀死cmd
var (
ctx context.Context
cancelFunc context.CancelFunc
cmd *exec.Cmd
resultChan chan *result
res *result
) // 创建了一个结果队列
resultChan = make(chan *result, 1000) // context: chan byte
// cancelFunc: close(chan byte) ctx, cancelFunc = context.WithCancel(context.TODO()) go func() {
var (
output []byte
err error
)
cmd = exec.CommandContext(ctx, "bash", "-c", "sleep 2;echo hello;") // 执行任务, 捕获输出
output, err = cmd.CombinedOutput() // 把任务输出结果, 传给main协程
resultChan <- &result{
err: err,
output: output,
}
}() // 继续往下走
time.Sleep(1 * time.Second) // 取消上下文
cancelFunc() // 在main协程里, 等待子协程的退出,并打印任务执行结果
res = <- resultChan // 打印任务执行结果
fmt.Println(res.err, string(res.output))
}