donglilian0061 2015-10-31 14:32
浏览 605
已采纳

golang-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条回答 默认 最新

  • douhan8610 2015-11-17 22:37
    关注

    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)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?