Domanda
Come faccio ben parse un elenco di parametri di programma e automatizzare la gestione "help" e / o "--version" (come "program [-d value] [--abc] [FILE1]
") in Go?
Soluzione 5
L'ho fatto solo per voi:
package main
import (
"fmt";
"os"
)
func main() {
for i, arg := range os.Args {
if arg == "-help" {
fmt.Printf ("I need somebody\n")
}else if arg == "-version" {
fmt.Printf ("Version Zero\n")
} else {
fmt.Printf("arg %d: %s\n", i, os.Args[i])
}
}
}
https://play.golang.org/p/XtNXG-DhLI
Prova:
$ ./8.out -help -version monkey business I need somebody Version Zero arg 3: monkey arg 4: business
Altri suggerimenti
Con il pacchetto 'bandiera': http://golang.org/pkg/flag/ . Non fa argomenti doppio trattino, però. Non c'è nulla che esattamente imita GNU comportamento getopt (ancora).
Google ha creato una getopt pacchetto (import "github.com/pborman/getopt"
), che fornisce la linea di comando più standard parsing (contro il pacchetto 'flag').
package main
import (
"fmt"
"os"
"github.com/pborman/getopt"
)
func main() {
optName := getopt.StringLong("name", 'n', "", "Your name")
optHelp := getopt.BoolLong("help", 0, "Help")
getopt.Parse()
if *optHelp {
getopt.Usage()
os.Exit(0)
}
fmt.Println("Hello " + *optName + "!")
}
$ ./hello --help
Usage: hello [--help] [-n value] [parameters ...]
--help Help
-n, --name=value Your name
$ ./hello --name Bob
Hello Bob!
Dalla sezione "riga di comando UI", sono disponibili diverse librerie in grado di analizzare parametri getopt a lungo .
ho provato, con un Go1.0.2:
- code.google.com/p/opts-go (Vedere la sua documentazione), che non è del tutto operativo .
- github.com/droundy/goopt (Vedere its documentazione ), che ha un set completo di esempi .
Esempio:
package main
import (
"fmt"
goopt "github.com/droundy/goopt"
)
func main() {
fmt.Println("flag")
goopt.NoArg([]string{"--abc"}, "abc param, no value", noabc)
goopt.Description = func() string {
return "Example program for using the goopt flag library."
}
goopt.Version = "1.0"
goopt.Summary = "goopt demonstration program"
goopt.Parse(nil)
}
func noabc() error {
fmt.Println("You should have an --abc parameter")
return nil
}
Altri parametri predefiniti forniti con goopt
:
--help Display the generated help message (calls Help())
--create-manpage Display a manpage generated by the goopt library (uses Author, Suite, etc)
--list-options List all known flags
go-bandiere è molto completo, BSD licenza, ed ha una chiara esempio .
var opts struct {
DSomething string `short:"d" description:"Whatever this is" required:"true"`
ABC bool `long:"abc" description:"Something"`
}
fileArgs, err := flags.Parse(&opts)
if err != nil {
os.Exit(1)
}
Un'altra opzione è Kingping che fornisce il supporto per tutte le chicche standard che ci si aspetta da un moderno riga di comando parsing biblioteca. E '--help
in più formati, sotto-comandi, i requisiti, i tipi, valori predefiniti, ecc E' inoltre ancora in fase di sviluppo. Sembra che gli altri suggerimenti qui non sono stati aggiornati in un po '.
package main
import (
"os"
"strings"
"gopkg.in/alecthomas/kingpin.v2"
)
var (
app = kingpin.New("chat", "A command-line chat application.")
debug = app.Flag("debug", "Enable debug mode.").Bool()
serverIP = app.Flag("server", "Server address.").Default("127.0.0.1").IP()
register = app.Command("register", "Register a new user.")
registerNick = register.Arg("nick", "Nickname for user.").Required().String()
registerName = register.Arg("name", "Name of user.").Required().String()
post = app.Command("post", "Post a message to a channel.")
postImage = post.Flag("image", "Image to post.").File()
postChannel = post.Arg("channel", "Channel to post to.").Required().String()
postText = post.Arg("text", "Text to post.").Strings()
)
func main() {
switch kingpin.MustParse(app.Parse(os.Args[1:])) {
// Register user
case register.FullCommand():
println(*registerNick)
// Post message
case post.FullCommand():
if *postImage != nil {
}
text := strings.Join(*postText, " ")
println("Post:", text)
}
}
E l'uscita --help
:
$ chat --help
usage: chat [<flags>] <command> [<flags>] [<args> ...]
A command-line chat application.
Flags:
--help Show help.
--debug Enable debug mode.
--server=127.0.0.1 Server address.
Commands:
help [<command>]
Show help for a command.
register <nick> <name>
Register a new user.
post [<flags>] <channel> [<text>]
Post a message to a channel.
Credo che quello che vuoi è docopt. Mi limiterò a vi rimando ad una precedente risposta ho postato per i dettagli.
Come una semplice libreria, dal momento che si dispone di agosto 2017 github.com/rsc/getopt
Per usare, definire le bandiere come al solito con la bandiera pacchetto. Poi introdurre alias per
getopt.Alias
chiamando:
getopt.Alias("v", "verbose")
O chiamare
getopt.Aliases
di definire un elenco di alias:
getopt.Aliases(
"v", "verbose",
"x", "xylophone",
)
E
In generale Go bandiera analisi è preferito per i nuovi programmi, perché non è così pedanti circa il numero di trattini utilizzati per invocare un flag (è possibile scrivere o
-verbose
--verbose
, e il programma non si cura).Questo pacchetto è pensato per essere utilizzato in situazioni in cui, per motivi di eredità, è importante utilizzare esattamente
getopt(3)
la sintassi, come ad esempio quando la riscrittura in Go uno strumento esistente che utilizza giàgetopt(3)
.