go语言将cmd stdout和stderr作为字符串返回而不是打印到控制台

2023-11-05 11:12

本文主要是介绍go语言将cmd stdout和stderr作为字符串返回而不是打印到控制台,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

go语言将cmd stdout和stderr作为字符串返回而不是打印到控制台

1、直接打印到控制台

从 golang 应用程序中执行 bash 命令,现在 stdout 和 stderr 直接进入控制台:

cmd.Stdout = os.Stdout 
cmd.Stderr = os.Stderr
package mainimport ("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)// Windowscmd := exec.Command("cmd", "/C", command)cmd.Stdout = os.Stdout // cmd.Stdout -> stdoutcmd.Stderr = os.Stderr // cmd.Stderr -> stderrokResult = trueerr := 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<-donelog.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 mainimport ("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)// Windowscmd := exec.Command("cmd", "/C", command)var outBuf, errBuf strings.Builder // or bytes.Buffercmd.Stdout = &outBufcmd.Stderr = &errBufokResult = trueerr := 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<-donelog.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
}

这篇关于go语言将cmd stdout和stderr作为字符串返回而不是打印到控制台的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/349469

相关文章

科研绘图系列:R语言扩展物种堆积图(Extended Stacked Barplot)

介绍 R语言的扩展物种堆积图是一种数据可视化工具,它不仅展示了物种的堆积结果,还整合了不同样本分组之间的差异性分析结果。这种图形表示方法能够直观地比较不同物种在各个分组中的显著性差异,为研究者提供了一种有效的数据解读方式。 加载R包 knitr::opts_chunk$set(warning = F, message = F)library(tidyverse)library(phyl

透彻!驯服大型语言模型(LLMs)的五种方法,及具体方法选择思路

引言 随着时间的发展,大型语言模型不再停留在演示阶段而是逐步面向生产系统的应用,随着人们期望的不断增加,目标也发生了巨大的变化。在短短的几个月的时间里,人们对大模型的认识已经从对其zero-shot能力感到惊讶,转变为考虑改进模型质量、提高模型可用性。 「大语言模型(LLMs)其实就是利用高容量的模型架构(例如Transformer)对海量的、多种多样的数据分布进行建模得到,它包含了大量的先验

Go Playground 在线编程环境

For all examples in this and the next chapter, we will use Go Playground. Go Playground represents a web service that can run programs written in Go. It can be opened in a web browser using the follow

go基础知识归纳总结

无缓冲的 channel 和有缓冲的 channel 的区别? 在 Go 语言中,channel 是用来在 goroutines 之间传递数据的主要机制。它们有两种类型:无缓冲的 channel 和有缓冲的 channel。 无缓冲的 channel 行为:无缓冲的 channel 是一种同步的通信方式,发送和接收必须同时发生。如果一个 goroutine 试图通过无缓冲 channel

C语言 | Leetcode C语言题解之第393题UTF-8编码验证

题目: 题解: static const int MASK1 = 1 << 7;static const int MASK2 = (1 << 7) + (1 << 6);bool isValid(int num) {return (num & MASK2) == MASK1;}int getBytes(int num) {if ((num & MASK1) == 0) {return

MiniGPT-3D, 首个高效的3D点云大语言模型,仅需一张RTX3090显卡,训练一天时间,已开源

项目主页:https://tangyuan96.github.io/minigpt_3d_project_page/ 代码:https://github.com/TangYuan96/MiniGPT-3D 论文:https://arxiv.org/pdf/2405.01413 MiniGPT-3D在多个任务上取得了SoTA,被ACM MM2024接收,只拥有47.8M的可训练参数,在一张RTX

如何确定 Go 语言中 HTTP 连接池的最佳参数?

确定 Go 语言中 HTTP 连接池的最佳参数可以通过以下几种方式: 一、分析应用场景和需求 并发请求量: 确定应用程序在特定时间段内可能同时发起的 HTTP 请求数量。如果并发请求量很高,需要设置较大的连接池参数以满足需求。例如,对于一个高并发的 Web 服务,可能同时有数百个请求在处理,此时需要较大的连接池大小。可以通过压力测试工具模拟高并发场景,观察系统在不同并发请求下的性能表现,从而

C语言:柔性数组

数组定义 柔性数组 err int arr[0] = {0}; // ERROR 柔性数组 // 常见struct Test{int len;char arr[1024];} // 柔性数组struct Test{int len;char arr[0];}struct Test *t;t = malloc(sizeof(Test) + 11);strcpy(t->arr,

C语言指针入门 《C语言非常道》

C语言指针入门 《C语言非常道》 作为一个程序员,我接触 C 语言有十年了。有的朋友让我推荐 C 语言的参考书,我不敢乱推荐,尤其是国内作者写的书,往往七拼八凑,漏洞百出。 但是,李忠老师的《C语言非常道》值得一读。对了,李老师有个官网,网址是: 李忠老师官网 最棒的是,有配套的教学视频,可以试看。 试看点这里 接下来言归正传,讲解指针。以下内容很多都参考了李忠老师的《C语言非

C 语言基础之数组

文章目录 什么是数组数组变量的声明多维数组 什么是数组 数组,顾名思义,就是一组数。 假如班上有 30 个同学,让你编程统计每个人的分数,求最高分、最低分、平均分等。如果不知道数组,你只能这样写代码: int ZhangSan_score = 95;int LiSi_score = 90;......int LiuDong_score = 100;int Zhou