英文:
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.String
和flag.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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论