使用“flag”包时,消除“提供了但未定义的标志”错误。

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

Get rid of "flag provided but not defined" when using "flag" package

问题

我正在使用Go语言制作一个API请求工具,并希望使用"flag"包。我使用flag.String定义了一个标志,但是当我输入一个不存在的标志时,程序会打印出"flag provided but not defined: {flag}"(其中{flag}是一个不存在的标志)。

我的代码如下:

package main

import "fmt"
import "flag"
import "os"

func main() {
	// 设置命令行参数
	apiRequestTool := flag.String("api", "", "")
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage: TestTestTest\n")
		os.Exit(1)
	}
	flag.Parse()
	
	// 检查API URL的值
	if *apiRequestTool == "" {
		fmt.Println("\"api\" Usage: --api [string]")
		os.Exit(1)
	}
}
英文:

I am making an API Request Tool using go, and want to use the "flag" package.
I have defined a flag using flag.String but when I enter a flag that does not exist
the program prints "flag provided but not defined: {flag}" (where {flag} is a flag that does not exist.)

My code is:

package main

import "fmt"
import "flag"
import "os"

func main() {
	// Set up command-line arguments
	apiRequestTool := flag.String("api", "", "")
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage: TestTestTest\n")
		os.Exit(1)
	}
	flag.Parse()
	
	// Check API URL value
	if *apiRequestTool == "" {
		fmt.Println("\"api\" Usage: --api [string]")
		os.Exit(1)
	}
}

答案1

得分: 4

flag.Stringflag.Parse等函数操作的是一个名为flag.CommandLine的导出的*flag.FlagSet单例。抑制该标志集的所有错误消息的一种方法是将其输出重定向到黑洞(例如在主函数的顶部):

flag.CommandLine.SetOutput(io.Discard)

在这之后,你认为烦人的错误消息将不会被打印出来:

$ go run main.go --whatever
Usage: TestTestTest
exit status 1
英文:

Functions like flag.String and flag.Parse operate on an exported *flag.FlagSet singleton named flag.CommandLine. One way of suppressing all error messages from that flag set consists in diverting its output to a black hole (e.g. at the top of your main function) like this:

<!-- language:go --->

flag.CommandLine.SetOutput(io.Discard)

After that, the error message that you perceive as annoying won't get printed:

<!-- language:shell --->

$ go run main.go --whatever
Usage: TestTestTest
exit status 1

huangapple
  • 本文由 发表于 2021年7月7日 18:35:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/68284402.html
匿名

发表评论

匿名网友

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

确定