문제

프로그램 매개 변수 목록을 잘 구문 분석하고 "-help"및/또는 "-version"(예 :”를 자동화하는 방법program [-d value] [--abc] [FILE1]") GO?

도움이 되었습니까?

해결책 5

나는 당신만을 위해 만들었습니다.

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

테스트:

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

다른 팁

'플래그'패키지 사용 : http://golang.org/pkg/flag/. 그러나 두 번의 논쟁을 수행하지 않습니다. GNU GetOpt 동작을 정확히 모방하는 것은 없습니다 (아직.)

Google은 a를 만들었습니다 getopt 패키지 (import "github.com/pborman/getopt") 더 표준 명령 줄 구문 분석 ( '플래그'패키지)을 제공합니다.

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!

"Command Line UI"섹션에서 구문 분석 할 수있는 여러 라이브러리가 있습니다. getopt-long 매개 변수.

나는 GO1.0.2로 시도했다.

예시:

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
}

제공된 기타 기본 매개 변수 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-flags 매우 완전하고 BSD 라이센스가 있으며 명확합니다. 예시.

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

또 다른 옵션입니다 킹핑 현대 사령관 구문 분석 라이브러리에서 기대할 수있는 모든 표준 케이크를 지원합니다. 가지고 있습니다 --help 여러 형식, 하위 명령, 요구 사항, 유형, 기본값 등으로도 여전히 개발 중입니다. 여기서 다른 제안이 한동안 업데이트되지 않은 것 같습니다.

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

그리고 --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.

나는 당신이 원하는 것이 docopt라고 생각합니다. 나는 당신을 추천 할 것입니다 이전 답변에 세부 사항을 게시했습니다.

간단한 도서관으로서, 당신은 2017 년 8 월부터 github.com/rsc/getopt

사용하려면 패키지 플래그로 평소와 같이 플래그를 정의하십시오. 그런 다음 호출하여 별칭을 소개합니다 getopt.Alias:

getopt.Alias("v", "verbose")

또는 전화 getopt.Aliases 별칭 목록을 정의하려면 :

getopt.Aliases(
    "v", "verbose",
    "x", "xylophone",
)

그리고:

일반적으로 Go Flag Parsing은 새로운 프로그램에 선호됩니다. 깃발을 호출하는 데 사용되는 대시의 수에 대해서는 pedantic이 아니기 때문입니다 (쓸 수 있습니다. -verbose 또는 --verbose, 그리고 프로그램은 신경 쓰지 않습니다).

이 패키지는 레거시 이유로 정확히 사용하는 것이 중요합니다. getopt(3) Go에서 다시 쓰는시기와 같은 구문은 이미 사용하는 기존 도구입니다. getopt(3).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top