英文:
In golang how can I write the stdout of an exec.Cmd to a file?
问题
我正在尝试运行一个shell命令,捕获标准输出并将输出写入文件。然而,似乎我漏掉了一些步骤,因为当程序退出时,我要写入的文件是空的。如何捕获命令的标准输出并将其写入文件?
package main
import (
"bufio"
"io"
"os"
"os/exec"
)
func main() {
cmd := exec.Command("echo", "'WHAT THE HECK IS UP'")
// 打开输出文件进行写入
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)
err = cmd.Start()
if err != nil {
panic(err)
}
go io.Copy(writer, stdoutPipe)
cmd.Wait()
}
以上是你提供的代码的翻译。
英文:
I am trying to run a shell command, capture stdout and write that output to a file. However, I seem to be missing a few steps, as the file I am trying to write is empty when the program exists. How can I capture the stdout of the command and write that to a file?
package main
import (
"bufio"
"io"
"os"
"os/exec"
)
func main() {
cmd := exec.Command("echo", "'WHAT THE HECK IS UP'")
// open the out file for writing
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)
err = cmd.Start()
if err != nil {
panic(err)
}
go io.Copy(writer, stdoutPipe)
cmd.Wait()
}
答案1
得分: 52
感谢#go-nuts
irc频道上的KirkMcDonald,我通过将输出文件分配给cmd.Stdout
来解决了这个问题,这意味着stdout直接写入文件。代码如下:
package main
import (
"os"
"os/exec"
)
func main() {
cmd := exec.Command("echo", "'WHAT THE HECK IS UP'")
// 打开输出文件进行写入
outfile, err := os.Create("./out.txt")
if err != nil {
panic(err)
}
defer outfile.Close()
cmd.Stdout = outfile
err = cmd.Start()
if err != nil {
panic(err)
}
cmd.Wait()
}
英文:
Thanks to KirkMcDonald on the #go-nuts
irc channel, I solved this by assigning the output file to cmd.Stdout
, which means that stdout writes directly to the file. It looks like this:
package main
import (
"os"
"os/exec"
)
func main() {
cmd := exec.Command("echo", "'WHAT THE HECK IS UP'")
// open the out file for writing
outfile, err := os.Create("./out.txt")
if err != nil {
panic(err)
}
defer outfile.Close()
cmd.Stdout = outfile
err = cmd.Start(); if err != nil {
panic(err)
}
cmd.Wait()
}
答案2
得分: 19
你还可以使用:
cmd.Stdout = os.Stdout
这将把所有 cmd 的输出重定向到操作系统的标准输出。
英文:
You can also use:
cmd.Stdout = os.Stdout
which will redirect all cmd output to the OS' standard output.
答案3
得分: 16
你需要刷新写入器。添加以下代码:
writer := bufio.NewWriter(outfile)
defer writer.Flush()
英文:
You need to flush the writer. Add the following:
writer := bufio.NewWriter(outfile)
defer writer.Flush()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论