Printing output to a command window when golang application is compiled with -ldflags -H=windowsgui

后端 未结 5 1763
野性不改
野性不改 2021-02-05 14:09

I have an application that usually runs silent in the background, so I compile it with

go build -ldflags -H=windowsgui 

To check

5条回答
  •  不思量自难忘°
    2021-02-05 14:23

    One problem with the solutions already posted here is that they redirect all output to the console, so if I run ./myprogram >file, the redirection to file gets lost. I've written a new module, github.com/apenwarr/fixconsole, that avoids this problem. You can use it like this:

    import (
            "fmt"
            "github.com/apenwarr/fixconsole"
            "os"
    )
    
    func main() {
            err := fixconsole.FixConsoleIfNeeded()
            if err != nil {
                    fmt.Fatalf("FixConsoleOutput: %v\n", err)
            }
            os.Stdout.WriteString(fmt.Sprintf("Hello stdout\n"))
            os.Stderr.WriteString(fmt.Sprintf("Hello stderr\n"))
    }
    

提交回复
热议问题