dtbl1231
2016-09-13 20:05
浏览 657
已采纳

如何从stdout输出到golang中的字符串

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

I need to get the output from stdout into a string value instead of a file. 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?

Thanks in advance

图片转代码服务由CSDN问答提供 功能建议

我有以下代码将数据从stdout输出到文件:

  cmd:= exec.Command(“ ls”,“ lh”)
outfile,err:= os.Create(“ ./ out.txt”)
if err!= nil {
 panic(err)  
} 
def 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的输出转换为字符串值而不是文件。 我该如何实现呢?

也许还有另一个函数可以让我将io.Copy行更改为io.Copy(myStringVariable,stdoutPipe),因为我需要读取输出 命令并对其进行一些处理?

预先感谢

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • dtgvl48608 2016-09-13 20:11
    最佳回答

    You don't need the pipe, writer, goroutine, etc. Just use Cmd.Output

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

    You can convert the output []byte to a string as needed with string(out)

    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题