2009-11-11 14 views

Respuesta

6

Lo hice sólo para usted:

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]) 
    } 
    } 
} 

ver también https://play.golang.org/p/XtNXG-DhLI

prueba:

 
$ ./8.out -help -version monkey business 
I need somebody 
Version Zero 
arg 3: monkey 
arg 4: business 
13

Utilice el paquete 'flag': http://golang.org/pkg/flag/. Sin embargo, no hace argumentos dobles. No hay nada que imita exactamente el comportamiento getopt GNU (todavía).

+11

hora de que alguien escribió uno. Ha estado fuera todo el día. –

+1

@Kinopiko: Eche un vistazo a go-mode.el en el directorio misc/emacs del repositorio de código fuente. – richq

+0

Aquí hay un enlace a un ejemplo que usa indicadores de línea de comandos: http: // golang.org/doc/go_tutorial.html # tmp_53 (El ejemplo "Echo" en el tutorial Go) –

8

De En la sección "Interfaz de usuario de línea de comando", tiene varias bibliotecas capaces de analizar getopt-long parameters.

lo intentaba, con un Go1.0.2:

Ejemplo:

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 
} 

Otros parámetros por defecto proporcionados 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 
5

go-flags es muy completo, BSD licencia, y tiene una clara example.

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) 
} 
+0

go-flags es bastante completo y también tiene la función de subcomando que yo quiero. Pero el documento es difícil de entender. Sugiero que leer código de ejemplo + hacer referencia a su documento sea lo mejor. (El enlace de ejemplo que señaló es muy útil.) –

12

Google ha creado un paquete getopt (import "github.com/pborman/getopt") que proporciona el análisis de línea de comandos más estándar (frente al paquete 'bandera').

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! 
+0

Vaya, estaba equivocado. El paquete fue escrito por Google y Google posee los derechos de autor. – yegle

3

Otra opción es Kingping que proporciona soporte para todos los objetos valiosos estándar que han llegado a esperar de una línea de comandos de análisis moderno de la biblioteca. Tiene --help en múltiples formatos, subcomandos, requisitos, tipos, valores predeterminados, etc. También está en desarrollo. Parece que las otras sugerencias aquí no han sido actualizadas por un tiempo.

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) 
    } 
} 

Y la salida --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.