英文:
Hide golang messages
问题
是否可以隐藏golang的消息?我给你展示一个例子:
package main
import (
"flag"
"fmt"
"os"
)
var signal = flag.String("z", "", "")
func main() {
flag.Usage = func() {
fmt.Printf("Usage: kata -z <command>\n\n")
fmt.Printf(" test\tTesting\n")
fmt.Printf(" version\tVersion\n")
fmt.Println("")
}
flag.Parse()
if len(os.Args) != 3 {
flag.Usage()
os.Exit(1)
}
switch *signal {
case "test":
fmt.Println("testing...")
case "version":
fmt.Println("0.0.1")
default:
fmt.Println("incorrect...")
}
}
这个应用程序向用户显示以下信息:
https://play.golang.org/p/oYwADdmlAJ
但是,如果我在命令行中输入kata -flag
,系统会返回:flag needs an argument:
或者 flag provided but not defined:
,以及之前展示给你的信息。
我想知道是否可以隐藏golang的消息?
附注:如果你不理解我的问题,我可以重新表述。
英文:
Is it possible to hide the golang messages? I show you an example:
package main
import (
"flag"
"fmt"
"os"
)
var signal = flag.String("z", "", "")
func main() {
flag.Usage = func() {
fmt.Printf("Usage: kata -z <command>\n\n")
fmt.Printf(" test\tTesting\n")
fmt.Printf(" version\tVersion\n")
fmt.Println("")
}
flag.Parse()
if len(os.Args) != 3 {
flag.Usage()
os.Exit(1)
}
switch *signal {
case "test":
fmt.Println("testing...")
case "version":
fmt.Println("0.0.1")
default:
fmt.Println("incorrect...")
}
}
This app show to user the next information:
https://play.golang.org/p/oYwADdmlAJ
But if I write in the command-line kata -flag
, the system returns: flag needs an argument:
or flag provided but not defined:
and the information that I show you before.
I would like to know if it's possible to hide the golang messages?
P.S.: If you don't understand my question, I can rephrase.
答案1
得分: 4
在flag
中使用全局函数实际上是通过一个名为flag.CommandLine
的全局flag.FlagSet
进行的。在内部,它将错误输出到一个默认为stderr的输出流。你可以通过将其显式设置为ioutil.Discard
来抑制这些消息:
flag.CommandLine.SetOutput(ioutil.Discard)
flag.Parse()
这将丢弃flag.Parse()
内部输出的所有消息。你也可以通过传递适当的io.Writer
将其记录到其他任何位置。
英文:
Using the global functions in flag
actually passes through to a global flag.FlagSet
called flag.CommandLine
. Internally, this prints errors to an output, which is stderr by default. You can suppress the messages by setting this explicitly to, for example, ioutil.Discard
:
flag.CommandLine.SetOutput(ioutil.Discard)
flag.Parse()
This will discard all messages output internally by flag.Parse()
. You could also log it to anywhere else you choose by passing in an appropriate io.Writer
.
答案2
得分: 0
我找到了一个解决方案:
之前的代码:
flag.Parse()
if len(os.Args) != 3 {
flag.Usage()
os.Exit(1)
}
现在的代码:
if len(os.Args) != 3 || os.Args[1] != "-z" {
flag.Usage()
os.Exit(1)
} else {
flag.Parse()
}
英文:
I have found a solution:
Before:
flag.Parse()
if len(os.Args) != 3 {
flag.Usage()
os.Exit(1)
}
Now:
if len(os.Args) != 3 || os.Args[1] != "-z" {
flag.Usage()
os.Exit(1)
} else {
flag.Parse()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论