将命令行字符串解析为Golang中的标志和参数

lau*_*ent 9 flags arguments package go command-line-arguments

我正在寻找一个包含一个字符串的包,并将其-v --format "some example" -i test解析为一段字符串,正确处理引号,空格等:

-v
--format
some example
-i
test
Run Code Online (Sandbox Code Playgroud)

我已经检查了内置flag包以及Github上的其他标志处理包,但它们似乎都没有处理将原始字符串解析为令牌的特殊情况.在尝试自己做之前,我宁愿寻找一个包,因为我确信有很多特殊情况需要处理.

有什么建议吗?

小智 8

看起来类似于shlex

import "github.com/google/shlex"
shlex.Split("one \"two three\" four") -> []string{"one", "two three", "four"}
Run Code Online (Sandbox Code Playgroud)

  • 应该是官方的答复。 (2认同)

lau*_*ent 7

有关信息,这是我最终创建的功能。

它将命令拆分为其参数。例如cat -v "some file.txt",将返回["cat", "-v", "some file.txt"]

它还可以正确处理转义字符,尤其是空格。因此cat -v some\ file.txt也将正确地分为["cat", "-v", "some file.txt"]

func parseCommandLine(command string) ([]string, error) {
    var args []string
    state := "start"
    current := ""
    quote := "\""
    escapeNext := true
    for i := 0; i < len(command); i++ {
        c := command[i]

        if state == "quotes" {
            if string(c) != quote {
                current += string(c)
            } else {
                args = append(args, current)
                current = ""
                state = "start"
            }
            continue
        }

        if (escapeNext) {
            current += string(c)
            escapeNext = false
            continue
        }

        if (c == '\\') {
            escapeNext = true
            continue
        }

        if c == '"' || c == '\'' {
            state = "quotes"
            quote = string(c)
            continue
        }

        if state == "arg" {
            if c == ' ' || c == '\t' {
                args = append(args, current)
                current = ""
                state = "start"
            } else {
                current += string(c)
            }
            continue
        }

        if c != ' ' && c != '\t' {
            state = "arg"
            current += string(c)
        }
    }

    if state == "quotes" {
        return []string{}, errors.New(fmt.Sprintf("Unclosed quote in command line: %s", command))
    }

    if current != "" {
        args = append(args, current)
    }

    return args, nil
}
Run Code Online (Sandbox Code Playgroud)


Dav*_*ave 5

如果参数在命令行上传递给您的程序,那么 shell 应该处理这个问题并os.Args正确填充。例如,在你的情况下os.Args[1:]等于

[]string{"-v", "--format", "some example", "-i", "test"}
Run Code Online (Sandbox Code Playgroud)

如果出于某种原因你只有字符串,并且你想模仿 shell 会用它做什么,那么我推荐像https://github.com/kballard/go-shellquote这样的包