我正在从golang应用程序执行 bash 命令。现在,stdout和stderr直接进入控制台:cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr但我希望stdout并stderr作为字符串变量从runBashCommandAndKillIfTooSlow函数返回,而不立即打印到控制台。如何实施?编码:package mainimport ( "fmt" "log" "os" "os/exec" "time")func main() { ok, outString, errString := runBashCommandAndKillIfTooSlow("ls -la", 2000) fmt.Println("ok") fmt.Println(ok) fmt.Println("outString") fmt.Println(outString) fmt.Println("errString") fmt.Println(errString)}/*run bash command and kill it if it works longer than "killInMilliSeconds" milliseconds*/func runBashCommandAndKillIfTooSlow(command string, killInMilliSeconds time.Duration) (okResult bool, stdout, stderr string) { fmt.Println("running bash command...") fmt.Println(command) cmd := exec.Command("sh", "-c", command) cmd.Stdout = os.Stdout // cmd.Stdout -> stdout cmd.Stderr = os.Stderr // cmd.Stderr -> stderr okResult = true err := cmd.Start() log.Printf("Waiting for command to finish...") done := make(chan error, 1) go func() { done <- cmd.Wait() }() select { case <-time.After(killInMilliSeconds * time.Millisecond): if err := cmd.Process.Kill(); err != nil { log.Fatal("failed to kill: ", err) okResult = false } <-done // allow goroutine to exit // log.Println("process killed") case err := <-done: if err != nil { log.Printf("process done with error = %v", err) okResult = false } } if err != nil { log.Fatal(err) okResult = false } return}顺便说一句,如果 bash 命令太慢(killInMilliSeconds参数),程序应该保持其杀死 bash 命令的能力。
3 回答
青春有我
TA贡献1784条经验 获得超8个赞
将输出设置为strings.Builder(在 Go 1.10 或更高版本中)或bytes.Buffer
var outbuf, errbuf strings.Builder // or bytes.Buffer
cmd.Stdout = &outbuf
cmd.Stderr = &errbuf
运行该命令后,您可以通过调用Builder.String()方法以字符串形式获取 stdout 和 stderr :
stdout := outbuf.String()
stderr := errbuf.String()
- 3 回答
- 0 关注
- 282 浏览
添加回答
举报
0/150
提交
取消