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

如何从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

  • 写回答

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

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了