本文介绍: go语言将cmd stdout和stderr作为字符串返回而不是打印到控制台
go语言将cmd stdout和stderr作为字符串返回而不是打印到控制台
1、直接打印到控制台
从 golang 应用程序中执行 bash 命令,现在 stdout 和 stderr 直接进入控制台:
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
package main
import (
"fmt"
"log"
"os"
"os/exec"
"time"
)
func main() {
ok, outString, errString := runBashCommandAndKillIfTooSlow("dir", 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)
// Linux
// cmd := exec.Command("sh", "-c", command)
// Windows
cmd := exec.Command("cmd", "/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
}
// allow goroutine to exit
<-done
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 命令的能力。
希望 stdout 和 stderr 作为字符串变量从 runBashCommandAndKillIfTooSlow 函数返回,而不立即打印到控
制台,如何实现。
2、不打印到控制台
将输出设置为 strings.Builder 或 bytes.Buffer:
var outbuf, errbuf strings.Builder // or bytes.Buffer
cmd.Stdout = &outbuf
cmd.Stderr = &errbuf
运行命令后,您可以通过调用 Builder.String() 获取字符串形式的标准输出和标准错误:
stdout := outbuf.String()
stderr := errbuf.String()
package main
import (
"fmt"
"log"
"os/exec"
"strings"
"time"
)
func main() {
ok, outString, errString := runBashCommandAndKillIfTooSlow("dir", 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)
// Linux
// cmd := exec.Command("sh", "-c", command)
// Windows
cmd := exec.Command("cmd", "/C", command)
var outBuf, errBuf strings.Builder // or bytes.Buffer
cmd.Stdout = &outBuf
cmd.Stderr = &errBuf
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
}
// allow goroutine to exit
<-done
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
}
stdout = outBuf.String()
stderr = errBuf.String()
return
}
原文地址:https://blog.csdn.net/qq_30614345/article/details/134063877
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_55161.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。