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

发布于 2024-08-30 08:00:37 字数 231 浏览 8 评论 0原文

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

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

func main() { ... }

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

How do I access command-line arguments in Go? They're not passed as arguments to main.

A complete program, possibly created by linking multiple packages, must have one package called main, with a function

func main() { ... }

defined. The function main.main() takes no arguments and returns no value.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

云仙小弟 2024-09-06 08:00:37

您可以使用 os.Args 变量。例如,

package main

import (
    "fmt"
    "os"
)

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

您还可以使用 flag 包,它实现了命令行标志解析。

You can access the command-line arguments using the os.Args variable. For example,

package main

import (
    "fmt"
    "os"
)

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

You can also use the flag package, which implements command-line flag parsing.

§普罗旺斯的薰衣草 2024-09-06 08:00:37

Flag 是一个很好的包。

来自 https://gobyexample.com/command-line-flags 的代码示例和注释,作者 < a href="https://markmcgranaghan.com/" rel="nofollow noreferrer">马克·麦克格拉纳汉 和 伊莱·本德斯基

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

Flag is a good package for that.

Code example and comments from https://gobyexample.com/command-line-flags by Mark McGranaghan and Eli Bendersky:

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())
}
桃扇骨 2024-09-06 08:00:37

快速回答:

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:] 保存程序的参数。
参考

Quick Answer:

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

Test: $ go run test.go 1 2 3 4 5

Out:

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

NOTE: os.Args provides access to raw command-line arguments. Note that the first value in this slice is the path to the program,
and os.Args[1:] holds the arguments to the program.
Reference

泼猴你往哪里跑 2024-09-06 08:00:37

命令行参数可以在 os.Args 中找到。在大多数情况下,尽管包 flag 更好,因为它为您进行参数解析。

Command line arguments can be found in os.Args. In most cases though the package flag is better because it does the argument parsing for you.

吻泪 2024-09-06 08:00:37

如果您只想要一个参数列表,彼得的答案正是您所需要的。

但是,如果您正在寻找类似于 UNIX 上现有功能的功能,那么您可以使用 go 实现docopt 的 a>。您可以在此处尝试一下。

docopt 将返回 JSON,然后您可以根据需要进行处理。

Peter's answer is exactly what you need if you just want a list of arguments.

However, if you're looking for functionality similar to that present on UNIX, then you could use the go implementation of docopt. You can try it here.

docopt will return JSON that you can then process to your heart's content.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文