英文:
Go - Combining cmd.StdoutPipe and Cmd.StderrPipe
问题
我想在Go中执行一个命令,并将其stdout和stderr合并为一个流。我写了这段代码,它只从stdout中读取,但我不知道如何将其与stderr合并:
package main
import (
"fmt"
"os"
"os/exec"
"bufio"
)
func runCommand() {
var (
err error
)
cmdName := "docker"
cmdArgs := []string{"build", "--no-cache=true", "--force-rm=true", "."}
cmd := exec.Command(cmdName, cmdArgs...)
cmdReader, err := cmd.StdoutPipe()
if err != nil {
fmt.Fprintln(os.Stderr, "Error creating StdoutPipe for Cmd", err)
}
scanner := bufio.NewScanner(cmdReader)
go func() {
for scanner.Scan() {
fmt.Printf("docker build out | %s\n", scanner.Text())
}
}()
err = cmd.Start()
if err != nil {
fmt.Fprintln(os.Stderr, "Error starting Cmd", err)
}
err = cmd.Wait()
if err != nil {
fmt.Fprintln(os.Stderr, "Error waiting for Cmd", err)
}
}
func main() {
runCommand()
}
谢谢所有的回答!
<details>
<summary>英文:</summary>
I would like to execute a command in Go, and combining its stdout and stderr into one stream. I wrote this code, its read only from the stdout, but I don't know how to I combine it with the stderr:
package main
import (
"fmt"
"os"
"os/exec"
"bufio"
)
func runCommand() {
var (
err error
)
cmdName := "docker"
cmdArgs := []string{"build", "--no-cache=true", "--force-rm=true", "."}
cmd := exec.Command(cmdName, cmdArgs...)
cmdReader, err := cmd.StdoutPipe()
if err != nil {
fmt.Fprintln(os.Stderr, "Error creating StdoutPipe for Cmd", err)
}
scanner := bufio.NewScanner(cmdReader)
go func() {
for scanner.Scan() {
fmt.Printf("docker build out | %s\n", scanner.Text())
}
}()
err = cmd.Start()
if err != nil {
fmt.Fprintln(os.Stderr, "Error starting Cmd", err)
}
err = cmd.Wait()
if err != nil {
fmt.Fprintln(os.Stderr, "Error waiting for Cmd", err)
}
}
func main() {
runCommand()
}
Thanks for all answers!
</details>
# 答案1
**得分**: 22
将标准输出(stdout)和标准错误(stderr)合并为一个读取器,将一个管道分配给Command.Stdout和Command.Stderr:
cmdReader, err := cmd.StdoutPipe()
cmd.Stderr = cmd.Stdout
<details>
<summary>英文:</summary>
To combine stdout and stderr to a single reader, assign a single pipe to Command.Stdout and Command.Stderr:
cmdReader, err := cmd.StdoutPipe()
cmd.Stderr = cmd.Stdout
</details>
# 答案2
**得分**: 0
使用函数[`io.MultiReader`][1]将多个读取器合并为一个:
outReader, err := cmd.StdoutReader()
if err != nil {
// 处理错误
}
errReader, err := cmd.StderrReader()
if err != nil {
// 处理错误
}
cmdReader := io.MultiReader(outReader, errReader)
[1]: https://golang.org/pkg/io/#MultiReader
<details>
<summary>英文:</summary>
Use the function [`io.MultiReader`][1] to combine multiple readers into one:
outReader, err := cmd.StdoutReader()
if err != nil {
// handle err
}
errReader, err := cmd.StderrReader()
if err != nil {
// handle err
}
cmdReader := io.MultiReader(outReader, errReader)
[1]: https://golang.org/pkg/io/#MultiReader
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论