如何从stdout输出到golang中的字符串 [英] How to get output from stdout into a string in golang
本文介绍了如何从stdout输出到golang中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码将数据从stdout输出到文件:
I have the following code which outputs data from stdout to a file:
cmd := exec.Command("ls","lh")
outfile, err := os.Create("./out.txt")
if err != nil {
panic(err)
}
defer outfile.Close()
stdoutPipe, err := cmd.StdoutPipe()
if err != nil {
panic(err)
}
writer := bufio.NewWriter(outfile)
defer writer.Flush()
err = cmd.Start()
if err != nil {
panic(err)
}
go io.Copy(writer, stdoutPipe)
cmd.Wait()
我需要将stdout的输出转换为字符串值而不是文件.我该如何实现?
I need to get the output from stdout into a string value instead of a file. How do I achieve that?
也许还有另一个函数可以让我将io.Copy行更改为io.Copy(myStringVariable,stdoutPipe),因为我需要读取命令的输出并对其进行一些处理?
Is there perhaps another function that will allow me to change the io.Copy line to go io.Copy(myStringVariable, stdoutPipe) as I need to read the output of the command and apply some processing to it?
预先感谢
推荐答案
You don't need the pipe, writer, goroutine, etc. Just use Cmd.Output
out, err := exec.Command("ls","lh").Output()
您可以根据需要使用 string(out)
这篇关于如何从stdout输出到golang中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文