Go exec.Command 转义字符

Go exec.Command escaping chars

Go 的 exec.Command 有这种非常奇怪的接收参数的方式。

我正在尝试执行一个简单的 ImageMagick 命令,但由于它解释我传递的字符串的方式而失败:

    cmd := exec.Command("convert", "out.png", "-resize", "50%", "-respect-parentheses", "+write", "mpr:out", "\(", "mpr:out", "-colorspace", "gray", "\)", "null:")
    fmt.Println(cmd)

    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    err := cmd.Run()
    if err != nil {
        log.Fatalf("cmd.Run() failed with %s\n", err)
    }

运行 上面的代码我得到错误:

/usr/local/bin/convert out.png -resize 50% -respect-parentheses +write mpr:out \( mpr:out -colorspace gray \) null:
convert: unable to open image '\(': No such file or directory @ error/blob.c/OpenBlob/3537.
convert: no decode delegate for this image format `' @ error/constitute.c/ReadImage/572.
convert: unable to open image '\)': No such file or directory @ error/blob.c/OpenBlob/3537.
convert: unable to open image '\)': No such file or directory @ error/blob.c/OpenBlob/3537.
convert: no decode delegate for this image format `' @ error/constitute.c/ReadImage/572.
2021/01/01 22:56:57 cmd.Run() failed with exit status 1
exit status 1

奇怪的是,如果我复制并粘贴打印的命令,它就会运行。
但由于某种原因,字符串“\(”被误解了。

有没有办法让编译器理解这个命令?

这与 Go 无关。当您使用 shell 执行程序时,shell 会解析您输入的命令行并为您想要 运行 的程序构造参数。当你 运行:

convert out.png -resize 50% -respect-parentheses +write mpr:out \( mpr:out -colorspace gray \) null:

shell 处理参数列表以构建包含 out.png-resize50%-respect-parentheses、[=15= 的参数数组], mpr:out, (, mpr:out, -colorspace, gray, ), null:.

所以你不应该通过"\(",而是通过(。匹配括号相同。