在命令行解析中引发自定义错误。

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

Raise custom error in command-line parsing

问题

我正在使用flag模块来解析我的标志,但是我想要至少有一个位置参数。当没有足够的位置参数时,我该如何显示使用帮助,就像在Python中使用parser.error一样?

目前,我正在手动调用os.Exit,但是对于应该是一个简单错误来说,这感觉非常繁琐:

  1. package main
  2. import "flag"
  3. import "fmt"
  4. import "os"
  5. func main() {
  6. flag.Parse()
  7. if flag.NArg() != 1 {
  8. println("This program needs exactly one argument")
  9. flag.Usage()
  10. os.Exit(2)
  11. }
  12. fmt.Printf("You entered %d characters", len(flag.Args()[0]))
  13. }
英文:

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:

  1. package main
  2. import &quot;flag&quot;
  3. import &quot;fmt&quot;
  4. import &quot;os&quot;
  5. func main() {
  6. flag.Parse()
  7. if flag.NArg() != 1 {
  8. println(&quot;This program needs exactly one argument&quot;)
  9. flag.Usage()
  10. os.Exit(2)
  11. }
  12. fmt.Printf(&quot;You entered %d characters&quot;, len(flag.Args()[0]))
  13. }

答案1

得分: 2

为了做类似这样的事情,我使用log包。

  1. package main
  2. import "flag"
  3. import "fmt"
  4. import "os"
  5. import "log"
  6. func main() {
  7. flag.Parse()
  8. if flag.NArg() != 1 {
  9. log.Fatalln("This program needs exactly one argument")
  10. }
  11. fmt.Printf("You entered %d characters", len(flag.Args()))
  12. }

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.

  1. package main
  2. import &quot;flag&quot;
  3. import &quot;fmt&quot;
  4. import &quot;os&quot;
  5. import &quot;log&quot;
  6. func main() {
  7. flag.Parse()
  8. if flag.NArg() != 1 {
  9. log.Fatalln(&quot;This program needs exactly one argument&quot;)
  10. }
  11. fmt.Printf(&quot;You entered %d characters&quot;, len(flag.Args()))
  12. }

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

huangapple
  • 本文由 发表于 2013年10月23日 21:27:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/19543011.html
匿名

发表评论

匿名网友

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

确定