如何访问传递给Go程序的命令行参数?


88

如何在Go中访问命令行参数?它们不会作为参数传递给main

一个完整的程序(可能是通过链接多个程序包创建的)必须具有一个名为main的程序包,并具有一个功能

func main() { ... }

定义。函数main.main()不带参数,也不返回值。


我会看一下flag内置的Golang模块。它使解析os.Args变得容易一些
Matej 2014年

另外,关于:“不返回值”,请注意,您可以调用os.Exit()以将特定的退出代码返回到调用过程。
马克·里德

Answers:


113

您可以使用os.Args变量访问命令行参数。例如,

package main

import (
    "fmt"
    "os"
)

func main() {
    fmt.Println(len(os.Args), os.Args)
}

您还可以使用flag软件包,该软件包实现命令行标志解析。



9

标志是一个很好的包装。

// [_Command-line flags_](http://en.wikipedia.org/wiki/Command-line_interface#Command-line_option)
// are a common way to specify options for command-line
// programs. For example, in `wc -l` the `-l` is a
// command-line flag.

package main

// Go provides a `flag` package supporting basic
// command-line flag parsing. We'll use this package to
// implement our example command-line program.
import "flag"
import "fmt"

func main() {

    // Basic flag declarations are available for string,
    // integer, and boolean options. Here we declare a
    // string flag `word` with a default value `"foo"`
    // and a short description. This `flag.String` function
    // returns a string pointer (not a string value);
    // we'll see how to use this pointer below.
    wordPtr := flag.String("word", "foo", "a string")

    // This declares `numb` and `fork` flags, using a
    // similar approach to the `word` flag.
    numbPtr := flag.Int("numb", 42, "an int")
    boolPtr := flag.Bool("fork", false, "a bool")

    // It's also possible to declare an option that uses an
    // existing var declared elsewhere in the program.
    // Note that we need to pass in a pointer to the flag
    // declaration function.
    var svar string
    flag.StringVar(&svar, "svar", "bar", "a string var")

    // Once all flags are declared, call `flag.Parse()`
    // to execute the command-line parsing.
    flag.Parse()

    // Here we'll just dump out the parsed options and
    // any trailing positional arguments. Note that we
    // need to dereference the pointers with e.g. `*wordPtr`
    // to get the actual option values.
    fmt.Println("word:", *wordPtr)
    fmt.Println("numb:", *numbPtr)
    fmt.Println("fork:", *boolPtr)
    fmt.Println("svar:", svar)
    fmt.Println("tail:", flag.Args())
}

1
看起来像是Go by
Example的

7

如果只需要一个参数列表,Peter的答案正是您需要的。

但是,如果你正在寻找类似的是,存在于UNIX的功能,那么你可以使用去实现docopt。您可以在这里尝试。

docopt将返回JSON,您可以将其处理为您的内心所愿。


1
可能需要的话太强了。建议“那么就可以”。
马特·乔纳

7

快速回答:

package main

import ("fmt"
        "os"
)

func main() {
    argsWithProg := os.Args
    argsWithoutProg := os.Args[1:]
    arg := os.Args[3]
    fmt.Println(argsWithProg)
    fmt.Println(argsWithoutProg)
    fmt.Println(arg)
}

测试: $ go run test.go 1 2 3 4 5

出:

[/tmp/go-build162373819/command-line-arguments/_obj/exe/modbus 1 2 3 4 5]
[1 2 3 4 5]
3

注意os.Args提供对原始命令行参数的访问。请注意,此片中的第一个值是程序的路径,并os.Args[1:]保存程序的参数。 参考


0

例如,您可以使用Golang标志包,

package main

import (
    "flag"
    "fmt"
)

func main() {

    wordPtr := flag.String("word", "default value", "a string for description")
    flag.Parse()
    fmt.Println("word:", *wordPtr)

}

用cli打电话

 go run main.go -word=hello
 
 

输出

word: hello
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.