英文:
How do I get all lines of output when running command with exec.Cmd.Run()?
问题
我正在使用glide来管理我的项目依赖。我创建了一个脚本来运行go test $(glide novendor)
(测试所有目录,排除_vendor/_目录)。虽然它可以工作,但运行命令的输出只显示第一行:
ok my/project/scripts 0.005s
以下是运行该脚本的部分代码:
// 获取要测试的路径(排除"vendor/"目录)
cmd := exec.Command("glide", "novendor")
var out bytes.Buffer
cmd.Stdout = &out
err = cmd.Run()
if err != nil {
log.Fatal("无法运行 `glide novendor`: ", err)
}
glidenovendor := []string{"test;"}
// 表示命令中的 "test ./src/... ./scripts/..." 部分
glidenovendor = append(glidenovendor, strings.Split(out.String(), " ")...)
// 运行 `go test ./src/... ./scripts/...`
cmd = exec.Command("go", glidenovendor...)
cmd.Stdout = os.Stdout
err = cmd.Run()
if err != nil {
log.Fatal("无法使用参数运行 `go test` 命令: ", cmd, err)
}
直接在命令行中运行该命令可以得到预期的所有输出行。
如何使我的脚本打印完整的输出?
英文:
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:
<!-- language: lang-go -->
// 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
得分: 0
原文翻译如下:
原来,在这行代码中:
glidenovendor = append(glidenovendor, strings.Split(out.String(), " ")...)
由于某种原因,会在glidenovendor
切片的最后一个字符串元素中添加一个换行符"\n"
。我仍然不知道为什么会这样。但是使用下面的代码片段将其移除后,脚本按预期运行:
// 从`glidenovendor`中的字符串中移除尾随的换行符
for i, v := range glidenovendor {
glidenovendor[i] = strings.Trim(v, "\n")
}
英文:
It turns out that line
glidenovendor = append(glidenovendor, strings.Split(out.String(), " ")...)
for some reason added a new line character "\n"
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:
<!-- language: lang-go -->
// Remove trailing LF from strings in `glidenovendor`
for i, v := range glidenovendor {
glidenovendor[i] = strings.Trim(v, "\n")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论