【问题标题】:golang: read cmd line arguments and additional parametersgolang:读取命令行参数和附加参数
【发布时间】:2021-12-25 08:27:34
【问题描述】:

我正在尝试使用下面的代码读取传递给go build.go build example-service 的额外参数 -

flag.Parse()

fmt.Println(flag.Args()) // Print "[build example-service]"

for _, cmd := range flag.Args() {
    switch cmd {
    case "build":
      log.Println("build", cmd) // Print "build build"
    }
}
            

我成功地将flag.Args() 打印为[build example-service],这是一个array 对象

我无法检索开关case 中的example-service arg,因为cmd 仅打印build build

【问题讨论】:

  • go build 将代码编译为可执行文件。它不执行代码。请准确显示您正在运行的命令

标签: go command-line command-line-arguments


【解决方案1】:

您要查找的是“命令行参数”主题。更多信息:https://gobyexample.com/command-line-arguments

os 包可以用于此目的。通过os.Args 数组,可以访问exe 文件地址(第一个索引)和参数(其他索引)。

还可以使用go run test.go arg1 arg2 arg3... 之类的命令运行您的文件。这里test.go 是我的测试文件名。

package main

import (
    "fmt"
    "os"
)

func main() {
    fmt.Printf("Input args are %v and type is %T", os.Args, os.Args)
}

运行go run test.go build example-service 命令后这段代码的输出是这样的:

Input args are [...\test.exe build example-service] and type is []string

您的代码可以修改为:

for _, cmd := range os.Args {
    switch cmd {
    case "build":
        log.Println("command: ", cmd)
    case "example-service":
        log.Println("command: ", cmd)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-06
    • 2013-05-27
    • 2023-04-01
    • 2017-02-21
    • 2016-03-25
    • 2012-09-18
    • 2016-01-28
    • 2011-08-30
    相关资源
    最近更新 更多