英文:
Raise custom error in command-line parsing
问题
我正在使用flag
模块来解析我的标志,但是我想要至少有一个位置参数。当没有足够的位置参数时,我该如何显示使用帮助,就像在Python中使用parser.error
一样?
目前,我正在手动调用os.Exit
,但是对于应该是一个简单错误来说,这感觉非常繁琐:
package main
import "flag"
import "fmt"
import "os"
func main() {
flag.Parse()
if flag.NArg() != 1 {
println("This program needs exactly one argument")
flag.Usage()
os.Exit(2)
}
fmt.Printf("You entered %d characters", len(flag.Args()[0]))
}
英文:
I'm using the <a href="http://golang.org/pkg/flag/">flag</a> module to parse my flags, but want to have at least one positional argument. How do I show the usage help when not enough positional arguments are present, as I would in python with parser.error
?
Currently, I am manually calling os.Exit
, but that feels really cumbersome for what should be a simple error:
package main
import "flag"
import "fmt"
import "os"
func main() {
flag.Parse()
if flag.NArg() != 1 {
println("This program needs exactly one argument")
flag.Usage()
os.Exit(2)
}
fmt.Printf("You entered %d characters", len(flag.Args()[0]))
}
答案1
得分: 2
为了做类似这样的事情,我使用log
包。
package main
import "flag"
import "fmt"
import "os"
import "log"
func main() {
flag.Parse()
if flag.NArg() != 1 {
log.Fatalln("This program needs exactly one argument")
}
fmt.Printf("You entered %d characters", len(flag.Args()))
}
log.Fatal()
及其相关方法(log.Fatalln()
,log.Fatalf()
等)都是辅助方法,它们首先执行log.Print()
,然后跟着执行os.Exit(1)
。
编辑--添加链接
http://golang.org/pkg/log/#Fatalln
英文:
To do things like this, I use the log
package.
package main
import "flag"
import "fmt"
import "os"
import "log"
func main() {
flag.Parse()
if flag.NArg() != 1 {
log.Fatalln("This program needs exactly one argument")
}
fmt.Printf("You entered %d characters", len(flag.Args()))
}
log.Fatal()
and it's sister methods (log.Fatalln()
, log.Fatalf()
etc) are all helpers that simply do log.Print()
and then follow it up with os.exit(1)
.
Edit -- Adding link
http://golang.org/pkg/log/#Fatalln
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论