简体   繁体   English

如何在golang中将stdout的输出转换为字符串

[英]How to get output from stdout into a string in golang

I have the following code which outputs data from stdout to a file: 我有以下代码将stdout中的数据输出到文件:

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()

I need to get the output from stdout into a string value instead of a file. 我需要将stdout的输出变为字符串值而不是文件。 How do I achieve that? 我如何实现这一目标?

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? 是否有另一个函数允许我将io.Copy行更改为io.Copy(myStringVariable,stdoutPipe),因为我需要读取命令的输出并对其应用一些处理?

Thanks in advance 提前致谢

You don't need the pipe, writer, goroutine, etc. Just use Cmd.Output 你不需要管道, 编写器 ,goroutine等。只需使用Cmd.Output

out, err := exec.Command("ls","lh").Output()

You can convert the output []byte to a string as needed with string(out) 您可以将输出转换[]bytestring根据需要用string(out)

You can set the file as the command's stdout 您可以将文件设置为命令的stdout

f, err := os.Create("./out.txt")
if err != nil {
    panic(err)
}
defer f.Close()

cmd := exec.Command("ls", "-lh")
cmd.Stdout = f
cmd.Stderr = os.Stderr

if err := cmd.Run(); err != nil {
    panic(err)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM