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

fmt.print()我正在使用一个代码中包含一些 s 的包,我想阻止它们打印到输出。我想在不更改包内代码的情况下抑制它们,而只需在我的main.go.

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


智慧大石
浏览 71回答 1
1回答

郎朗坤

是的,只需转移os.Stdout和/或os.Stderr例如:package mainimport (    "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 mainimport (    "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")}
打开App,查看更多内容
随时随地看视频慕课网APP