英文:
How to print buffer to stdout but also capture as string?
问题
我知道如何捕获exec.Command
的输出,但我也想将其流式传输到stdout
并同时捕获它。谢谢任何建议!
package main
import (
"bytes"
"fmt"
"os/exec"
)
func main() {
cmd := exec.Command("ls")
var out bytes.Buffer
cmd.Stdout = &out
cmd.Run()
fmt.Println(out.String())
}
我会将代码翻译为中文并返回给你。
英文:
I know how to capture the output of a exec.Command
but I would like to also stream it to stdout
while still capturing it.
Thanks for any input!
package main
import (
"bytes"
"fmt"
"os/exec"
)
func main() {
cmd := exec.Command("ls")
var out bytes.Buffer
cmd.Stdout = &out
cmd.Run()
fmt.Println(out.String())
}
答案1
得分: 3
package main
import (
"io"
"os"
"bytes"
"fmt"
"os/exec"
)
func main() {
cmd := exec.Command("ls")
var out bytes.Buffer
w := io.MultiWriter(os.Stdout, &out)
cmd.Stdout = w
fmt.Printf("===标准输出:===\n")
cmd.Run()
fmt.Printf("\n===变量:===\n")
fmt.Println(out.String())
}
<details>
<summary>英文:</summary>
### Example using [`io.MultiWriter`][3]
```go
package main
import (
"io"
"os"
"bytes"
"fmt"
"os/exec"
)
func main() {
cmd := exec.Command("ls")
var out bytes.Buffer
w := io.MultiWriter(os.Stdout, &out)
cmd.Stdout = w
fmt.Printf("===Stdout:===\n")
cmd.Run()
fmt.Printf("\n===Variable:===\n")
fmt.Println(out.String())
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论