dreamy1992 2016-08-25 17:31
浏览 306
已采纳

Golang-执行命令,其中一部分为空格

I am running a command through the os/exec package that is called like this:

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

The function I have written to execute command line calls is:

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
}

The strings.Fields command splits the command on spaces and that is used as the string array to pass to the exec.Command function. The problem is that it is splitting the filename into different parts because of the space when that filepath needs to stay together. Even if I format the string array correctly so the filepath is in one part, the exec.Command still fails because there is a space. I need to be able to execute this script to honor the filepath as one argument with spaces.

  • 写回答

2条回答 默认 最新

  • doujian1050 2016-08-25 20:59
    关注

    Well, I figured it out.

    var parts []string
    preParts := strings.FieldsFunc(command, f)
    for i := range preParts {
        part := preParts[i]
        parts = append(parts, strings.Replace(part, "'", "", -1))
    }
    

    I needed to remove the single quotes from the arg passed into the exec.Command function.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里