gpt4 book ai didi

go - 如何停止 fmt.print() 打印到输出?

转载 作者:行者123 更新时间:2023-12-01 22:39:45 24 4
gpt4 key购买 nike

我使用的包在代码中包含一些 fmt.print(),我想阻止它们打印到输出。我想在不更改包内代码的情况下抑制它们,而只是通过向我的 main.go 添加一些行。

是否可以强制 fmt 不将打印记录到输出中?

最佳答案

是的,只需转移 os.Stdout 和/或 os.Stderr 例如:

package main

import (
"fmt"
"os"
)

func main() {
temp := os.Stdout
os.Stdout = nil // turn it off
packageFunctions() // call you package functions here
os.Stdout = temp // restore it
fmt.Println("Bye")
}
func packageFunctions() {
fmt.Println("Hi")
}

输出:

Bye

您可以将其转移到一个临时文件中:

package main

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

func main() {
tmpfile, err := ioutil.TempFile("", "example")
if err != nil {
log.Fatal(err)
}
fmt.Println(tmpfile.Name())
// defer os.Remove(tmpfile.Name()) // clean up

temp := os.Stdout
os.Stdout = tmpfile
packageFunctions() // call you package functions here

if err := tmpfile.Close(); err != nil {
log.Fatal(err)
}

os.Stdout = temp // restore it
fmt.Println("Bye")
}
func packageFunctions() {
fmt.Println("Hi")
}

然后看:

How to copy os.Stdout output to string variable

How can stdout be captured or suppressed for Go(lang) testing?

关于go - 如何停止 fmt.print() 打印到输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58682376/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com