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

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

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 &quot;flag&quot;
import &quot;fmt&quot;
import &quot;os&quot;

func main() {
  flag.Parse()
  if flag.NArg() != 1 {
  	println(&quot;This program needs exactly one argument&quot;)
  	flag.Usage()
  	os.Exit(2)
  }
  fmt.Printf(&quot;You entered %d characters&quot;, 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 &quot;flag&quot;
import &quot;fmt&quot;
import &quot;os&quot;
import &quot;log&quot;

func main() {
  flag.Parse()
  if flag.NArg() != 1 {
    log.Fatalln(&quot;This program needs exactly one argument&quot;)
  }
  fmt.Printf(&quot;You entered %d characters&quot;, 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

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:

确定