`os.Stdout`和`io.MultiWriter`之间的区别是什么?

huangapple go评论82阅读模式
英文:

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.Stdoutmultiwriter 之间的差异?

英文:

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.MultiWriteros.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)

huangapple
  • 本文由 发表于 2015年10月31日 22:32:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/33452726.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定