dongrou839975 2015-11-09 08:18
浏览 320
已采纳

使用exec.Cmd.Run()运行命令时,如何获取所有输出行?

I'm using glide to manage dependencies on my project. I created a script that runs go test $(glide novendor) (which tests all directories, excluding the vendor/ one) for me. While it works, the output for the run command doesn't go beyond the 1st line:

ok my/project/scripts 0.005s

Here is the portion of the script that runs it:

// Get the paths to test (excluding the "vendor/" directory)
cmd := exec.Command("glide", "novendor")
var out bytes.Buffer
cmd.Stdout = &out
err = cmd.Run()
if err != nil {
    log.Fatal("Could not run `glide novendor`: ", err)
}
glidenovendor := []string{"test"}
// Represents the "test ./src/... ./scripts/..." portion of the command
glidenovendor = append(glidenovendor, strings.Split(out.String(), " ")...)

// Run `go test ./src/... ./scripts/...`
cmd = exec.Command("go", glidenovendor...)
cmd.Stdout = os.Stdout
err = cmd.Run()
if err != nil {
    log.Fatal("Could not run `go test` command with args: ", cmd, err)
}

Running the command directly on my shell gives me all lines of out put as expected.

How do I make my script print the entire output?

  • 写回答

1条回答 默认 最新

  • douyongdao4046 2015-11-09 08:53
    关注

    It turns out that line

    glidenovendor = append(glidenovendor, strings.Split(out.String(), " ")...)

    for some reason added a new line character " " to the last string element of the glidenovendor slice. I still have no idea why. But removing it with the snippet below got the script running as expected:

    // Remove trailing LF from strings in `glidenovendor`
    for i, v := range glidenovendor {
        glidenovendor[i] = strings.Trim(v, "
    ")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格