代码之家  ›  专栏  ›  技术社区  ›  gcstr

去执行。命令转义字符

  •  0
  • gcstr  · 技术社区  · 5 年前

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

    0 回复  |  直到 5 年前
        1
  •  1
  •   Burak Serdar    5 年前

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

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

    shell处理参数列表以构造一个参数数组,其中包含 out.png , -resize , 50% , -respect-parentheses , +write , mpr:out , ( , mpr:输出 , -colorspace , gray , ) , null: .

    所以你不应该通过 "\\(" ,但是通过 ( 。匹配的括号也是如此。