在其中一部分中执行带空格的命令 [英] Executing command with spaces in one of the parts
问题描述
我正在通过 os/exec 程序包运行命令,如下所示:
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
}
strings.Fields
命令在空格中分割命令,该命令用作传递给exec.Command函数的字符串数组.问题在于,由于filepath
需要保持在一起的空间,它会将文件名拆分为不同的部分.即使我正确设置了字符串数组的格式,使filepath
处于同一部分,但由于存在空格,因此exec.Command
仍然会失败.我需要能够执行此脚本,以将filepath
用作带空格的一个参数.
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.
推荐答案
好吧,我知道了.
var parts []string
preParts := strings.FieldsFunc(command, f)
for i := range preParts {
part := preParts[i]
parts = append(parts, strings.Replace(part, "'", "", -1))
}
我需要从传递给exec.Command函数的arg中删除单引号.
I needed to remove the single quotes from the arg passed into the exec.Command function.
这篇关于在其中一部分中执行带空格的命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!