在其中一个部分执行带有空格的命令

我正在通过调用如下的os/exec包运行命令:


out, err := Exec("ffprobe -i '/media/Name of File.mp3' -show_entries format=duration -v quiet -of csv=p=0", true, true)

我编写的用于执行命令行调用的函数是:


func Exec(command string, showOutput bool, returnOutput bool) (string, error) {

    log.Println("Running command: " + command)


    lastQuote := rune(0)

    f := func(c rune) bool {

        switch {

        case c == lastQuote:

            lastQuote = rune(0)

            return false

        case lastQuote != rune(0):

            return false

        case unicode.In(c, unicode.Quotation_Mark):

            lastQuote = c

            return false

        default:

            return unicode.IsSpace(c)

        }

    }


    parts := strings.FieldsFunc(command, f)

    //parts = ["ffprobe", "-i", "'/media/Name of File.mp3'", "-show_entries", "format=duration", "-v", "quiet", "-of", "csv=p=0"]

    if returnOutput {

        data, err := exec.Command(parts[0], parts[1:]...).Output()

        if err != nil {

            return "", err

        }

        return string(data), nil

    } else {

        cmd := exec.Command(parts[0], parts[1:]...)

        if showOutput {

            cmd.Stderr = os.Stderr

            cmd.Stdout = os.Stdout

        }

        err := cmd.Run()

        if err != nil {

            return "", err

        }

    }


    return "", nil

}

该strings.Fields命令将命令拆分为空格,并将其用作字符串数组以传递给 exec.Command 函数。问题在于它将文件名分成不同的部分,因为filepath需要保持在一起的空间。即使我正确格式化了字符串数组,所以filepath它在一个部分中,exec.Command仍然会失败,因为有一个空格。我需要能够执行此脚本以将filepath空格作为一个参数。


慕神8447489
浏览 180回答 2
2回答

慕桂英3389331

您可以strings.Split(s, ":")在特殊字符上使用并使用反引号:进行切换 ,例如 这个工作示例(The Go Playground):"package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "strings")func main() {&nbsp; &nbsp; command := `ffprobe : -i "/media/Name of File.mp3" : -show_entries format=duration : -v quiet : -of csv=p=0`&nbsp; &nbsp; parts := strings.Split(command, ":")&nbsp; &nbsp; for i := 0; i < len(parts); i++ {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(strings.Trim(parts[i], " "))&nbsp; &nbsp; }}输出:ffprobe-i "/media/Name of File.mp3"-show_entries format=duration-v quiet-of csv=p=0在(删除)cmd.Args之后尝试打印:cmd := exec.Command("ffprobe", s...).Output()对于 _, v := 范围 cmd.Args { fmt.Println(v) }像这样,找出你的参数发生了什么:s := []string{"-i '/media/Name of File.mp3'", "-show_entries format=duration", "-v quiet", "-of csv=p=0"}cmd := exec.Command("ffprobe", s...)for _, v := range cmd.Args {&nbsp; &nbsp; fmt.Println(v)}cmd.Args = []string{"ffprobe", "-i '/media/Name of File.mp3'", "-show_entries format=duration", "-v quiet", "-of csv=p=0"}fmt.Println()for _, v := range cmd.Args {&nbsp; &nbsp; fmt.Println(v)}看:// Command returns the Cmd struct to execute the named program with// the given arguments.//// It sets only the Path and Args in the returned structure.//// If name contains no path separators, Command uses LookPath to// resolve the path to a complete name if possible. Otherwise it uses// name directly.//// The returned Cmd's Args field is constructed from the command name// followed by the elements of arg, so arg should not include the// command name itself. For example, Command("echo", "hello")func Command(name string, arg ...string) *Cmd {&nbsp; &nbsp; cmd := &Cmd{&nbsp; &nbsp; &nbsp; &nbsp; Path: name,&nbsp; &nbsp; &nbsp; &nbsp; Args: append([]string{name}, arg...),&nbsp; &nbsp; }&nbsp; &nbsp; if filepath.Base(name) == name {&nbsp; &nbsp; &nbsp; &nbsp; if lp, err := LookPath(name); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cmd.lookPathErr = err&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cmd.Path = lp&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return cmd}编辑3-试试这个package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "os/exec")func main() {&nbsp; &nbsp; cmd := exec.Command(`ffprobe`, `-i "/media/Name of File.mp3"`, `-show_entries format=duration`, `-v quiet`, `-of csv=p=0`)&nbsp; &nbsp; for _, v := range cmd.Args {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(v)&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(cmd.Run())}

慕妹3146593

嗯,我想通了。var parts []stringpreParts := strings.FieldsFunc(command, f)for i := range preParts {&nbsp; &nbsp; part := preParts[i]&nbsp; &nbsp; parts = append(parts, strings.Replace(part, "'", "", -1))}我需要从传递给 exec.Command 函数的 arg 中删除单引号。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go