在缓冲区接收数据时将 exec.Command 输出复制到文件

Copy exec.Command output to file as the buffer receives data

我有一个脚本可以在 运行 时将相当多的文本转储到 STDOUT 中。我试图执行这个脚本并将输出写入一个文件,而不是一次将整个缓冲区保存在内存中。 (我们说的是此脚本一次输出的许多兆字节的文本。)

以下工作正常,但因为我在多个 goroutine 中执行此操作,所以我的内存消耗猛增到 > 5GB,我真的很想避免:

var out bytes.Buffer
cmd := exec.Command("/path/to/script/binary", "arg1", "arg2")
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
    log.Fatal(err)
}
out.WriteTo(io) // io is the writer connected to the new file

理想情况下,当 out 填满时,我想将其清空到我的目标文件中以保持低内存使用率。我试过将其更改为:

cmd := exec.Command("/path/to/script/binary", "arg1", "arg2")
cmd.Start()
stdout, _ := cmd.StdoutPipe()
r := *bufio.NewReader(stdout)
r.WriteTo(io)
cmd.Wait()

然而,当我打印出这些变量时,stdout<nil>r{[0 0 0 0 0...]},并且 r.WriteTo 恐慌:invalid memory address or nil pointer dereference

是否可以在生成时写入 cmd 的输出以降低内存使用量?谢谢!

为什么不直接写入文件?

file, _ := os.Create("/some/file")
cmd.Stdout = file

或者使用您的 io 东西(顺便说一下,这是一个糟糕的变量名称,因为它是 a) 标准库包的名称,b) 模棱两可——它是什么意思?)

cmd.Stdout = io