英文:
golang - difference between os.stdout and multiwriter
问题
我有这段代码来运行 zsh
并将其输出记录到一个输出文件中。
package main
import (
"io"
"os"
"os/exec"
)
func main() {
cmd := exec.Command("zsh")
f, _ := os.Create("log.txt")
multiWriter := io.MultiWriter(os.Stdout, f)
cmd.Stdout = multiWriter
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
cmd.Run()
}
func haltOnError(err error) {
if err != nil {
panic(err)
}
}
当程序执行时,输入 ls
将输出:
foo
bar
而如果我让 cmd.Stdout = os.Stdout
,则正确显示为:
foo bar
是什么导致了 os.Stdout
和 multiwriter
之间的差异?
英文:
I have this code to run zsh
and log its output to an output file.
package main
import (
"io"
"os"
"os/exec"
)
func main() {
cmd := exec.Command("zsh")
f, _ := os.Create("log.txt")
multiWriter := io.MultiWriter(os.Stdout, f)
cmd.Stdout = multiWriter
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
cmd.Run()
}
func haltOnError(err error) {
if err != nil {
panic(err)
}
}
when the program executes, typing ls
will output
foo
bar
while if I let cmd.Stdout = os.Stdout
, it displays correctly as
foo bar
What leads to the differences between os.Stdout
and multiwriter
?
答案1
得分: 3
根据@Time和@wldsvc的评论,问题的原因是ls
使用isatty
来选择默认的输出格式,在这种情况下,使用io.MultiWriter
和os.Stdout
会根据isatty
的结果做出不同的决策。
提出的解决方案是通过使用参数来强制ls
的输出格式(man ls):
-C 按列显示
-x 按行而不是列显示
-1 每行显示一个文件
(将答案记录为未解答列表中的高优先级问题)
英文:
Based on comments by @Time and @wldsvc
The cause of the problem is that isatty
is used by ls
to choose the default output format, in this case the use of io.MultiWriter
and os.Stdout
result in different decisions based on the result of isatty
.
The proposed solution was to force the output format of ls
by use of the parameters (man ls):
-C list by columns
-x list by lines instead of columns
-1 list one file per line
(documenting answer as show quiet high on unanswered list)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论