登录
首页 >  Golang >  Go问答

执行 exec.Command 转移符

来源:stackoverflow

时间:2024-03-26 22:36:33 439浏览 收藏

在使用 Go 的 `exec.Command` 执行外部命令时,遇到将字符串解释为参数的问题。当命令包含特殊字符如括号时,Go 编译器会将其误解。此问题与 Go 无关,而是与 shell 解析命令行的方式有关。shell 将传入的字符串分割为参数数组,而括号应该直接传递给要执行的程序。因此,需要将 `\\(` 替换为直接的括号字符 `(`。

问题内容

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编译器理解这个命令?


解决方案


这与 go 没有具体关系。当您使用 shell 执行程序时,shell 会解析您输入的命令行并为您要运行的程序构造参数。当你跑步时:

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

shell 处理参数列表以构造一个参数数组,其中包含 out.png-resize50%-respect-parentheses+writempr:out、zq bczqb(,mpr:out-颜色空间gray)null:

因此,您不应传递 "\\(",而应传递 (。匹配的括号相同。

终于介绍完啦!小伙伴们,这篇关于《执行 exec.Command 转移符》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>