如何通过管道从os.Exec将stdout传输到文件和终端? [英] How to pipe stdout from os.Exec to file and to terminal?

查看:36
本文介绍了如何通过管道从os.Exec将stdout传输到文件和终端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过管道将os.Exec的stdout发送到文件,也发送到终端?

How to pipe stdout for os.Exec to file but also to terminal?

我已经尝试过:

go func() {
    scanner := bufio.NewScanner(stdout)
    writer := bufio.NewWriter(logFile)
    for scanner.Scan() {
        log.Debugln(scanner.Text())
        writer.WriteString(scanner.Text())
    }
    writer.Flush()
}()

但是 writer.WriteString(scanner.Text())在文件中丢失了 \ n .如何让他们回来?也许有一些更优雅的管道解决方案?

But writer.WriteString(scanner.Text()) losts \n in file. How to got them back? Maybe there is some more elegant solution with pipes?

推荐答案

创建 io.MultiWriter 带有参数os.Stdout和文件.将 Cmd.Stdout 设置为多重写入器.运行命令.

Create a io.MultiWriter with arguments os.Stdout and the file. Set Cmd.Stdout to the multiwriter. Run the command.

 cmd := exec.Command(name, args...)
 cmd.Stdout = io.MultiWriter(os.Stdout, file)
 err := cmd.Run()

如果要逐行写入log.Debugf和其他文件,请执行以下操作:

If you want to write line by line to log.Debugf and other files, then do the following:

go func() {
    scanner := bufio.NewScanner(stdout)
    writer := bufio.NewWriter(io.MultiWriter(os.Stdout, file))
    for scanner.Scan() {
        log.Debugln(scanner.Text())
        writer.Write(scanner.Bytes())
        writer.WriteByte('\n')  // add line separator
    }
    writer.Flush()
}()

此代码假定输入中的行分隔符为\ n.

This code assumes that the line separator in the input is \n.

这篇关于如何通过管道从os.Exec将stdout传输到文件和终端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆