2

I'm using the flag 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]))
}
phihag
  • 278,196
  • 72
  • 453
  • 469

1 Answers1

2

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

bclymer
  • 6,679
  • 2
  • 27
  • 36