How to capture fmt.Print ouput in a text file in Golang

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

How to capture fmt.Print ouput in a text file in Golang

问题

有一些我想保存到.txt文件中的fmt.Print语句。

我不想存储所有的打印语句。我可以这样做吗?

英文:

There are certain fmt.Print statements that I want to save into a .txt file.

I don't want to store all print statments. Can I do this ?

答案1

得分: 7

package main

import (
    "fmt"
    "io"
    "log"
    "os"
)

func main() {
    file, err := os.Create("myfile")
    if err != nil {
        log.Fatal(err)
    }

    mw := io.MultiWriter(os.Stdout, file)
    fmt.Fprintln(mw, "这一行将被写入标准输出和文件中")
}

这是一个Go语言的代码示例,它创建了一个文件并将一行文本同时写入标准输出和文件中。

英文:
package main

import (
    "fmt"
    "io"
    "log"
    "os"
)

func main() {
    file, err := os.Create("myfile")
    if err != nil {
        log.Fatal(err)
    }

    mw := io.MultiWriter(os.Stdout, file)
    fmt.Fprintln(mw, "This line will be written to stdout and also to a file")
}

答案2

得分: 2

使用fmt.Fprint()方法来调用你想保存到文件的内容。还有fmt.Fprintf()fmt.Fprintln()

这些函数的第一个参数是一个目标io.Writer,你可以将你的文件(*os.File)传递给它。

例如:

f, err := os.Open("data.txt")
if err != nil {
    log.Fatal(err)
}
defer f.Close()

fmt.Println("This goes to standard output.")
fmt.Fprintln(f, "And this goes to the file")
fmt.Fprintf(f, "Also to file, with some formatting. Time: %v, line: %d\n",
    time.Now(), 2)

如果你希望所有的fmt.PrintXX()调用都写入到一个你无法控制的文件(例如,你不能将它们改为fmt.FprintXX(),因为它们是另一个库的一部分),你可以临时更改os.Stdout,这样所有后续的fmt.PrintXX()调用都会写入到你设置的输出中,例如:

// 临时将你的文件设置为标准输出(并保存旧的标准输出)
old, os.Stdout = os.Stdout, f

// 现在所有的 fmt.PrintXX() 调用都输出到 f
somelib.DoSomething()

// 恢复原始的标准输出
os.Stdout = old
英文:

Use the fmt.Fprint() method for calls you want to save to a file. There are also fmt.Fprintf() and fmt.Fprintln().

These functions take a destination io.Writer as the first argument, to which you can pass your file (*os.File).

For example:

f, err := os.Open("data.txt")
if err != nil {
	log.Fatal(err)
}
defer f.Close()

fmt.Println("This goes to standard output.")
fmt.Fprintln(f, "And this goes to the file")
fmt.Fprintf(f, "Also to file, with some formatting. Time: %v, line: %d\n",
	time.Now(), 2)

If you want all fmt.PrintXX() calls to go to the file which you have no control over (e.g. you can't change them to fmt.FprintXX() because they are part of another library), you may change os.Stdout temporarily, so all further fmt.PrintXX() calls will write to the output you set, e.g.:

// Temporarily set your file as the standard output (and save the old)
old, os.Stdout = os.Stdout, f

// Now all fmt.PrintXX() calls output to f
somelib.DoSomething()

// Restore original standard output
os.Stdout = old

huangapple
  • 本文由 发表于 2016年11月8日 19:00:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/40485179.html
匿名

发表评论

匿名网友

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

确定