繁体   English   中英

由于双引号导致 Windows 上的 Golang exec.Command 错误

[英]Golang exec.Command error on Windows due to double quote

我有这个评论,它下载了一个简单的文件:

var tarMode = "xf"
cmdEnsure = *exec.Command("cmd", "/C", fmt.Sprintf(`curl -L -o file.zip "https://drive.google.com/uc?export=download&id=theIDofthefile" && tar -%s file.zip`, tarMode))
err := cmdEnsure.Run()

go 中的此代码将出错,因为: curl: (1) Protocol ""https" not supported or disabled in libcurl

现在我明白这是由于我的双引号造成的。 但是,如果我删除 if,我得到Id is not recognized as an internal or external command, operable program or batch file ,这是有道理的,因为& simple 意味着在cmd中执行另一个命令。

那么执行此类下载命令和提取的选项是什么。 该命令本身在cmd上运行良好。

我发现最好不要尝试在一次执行中组合多个命令。 下面的工作很好,您不必担心 escaping 和可移植性,您还可以获得更好的错误处理。

package main

import (
    "fmt"
    "os/exec"
)

func main() {
    if b, err := exec.Command("curl", "-L", "-o", "file.zip", "https://drive.google.com/uc?export=download&id=theIDofthefile").CombinedOutput(); err != nil {
        fmt.Printf("%+v, %v", string(b), err)
        return
    }

    if b, err := exec.Command("tar", "-x", "-f", "file.zip").CombinedOutput(); err != nil {
        fmt.Printf("%+v, %v", string(b), err)
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM