英文:
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.
现在我明白这是由于我的双引号引起的。然而,如果我将其移除,我会得到Id is not recognized as an internal or external command, operable program or batch file
,这是有道理的,因为&
只是在cmd
中执行另一个命令。
那么,我执行这样的下载命令和解压缩有哪些选项呢?这个命令本身在cmd
中可以正常运行。
英文:
I have this comment, which downloads a simple file:
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()
This code in go will error because:
curl: (1) Protocol ""https" not supported or disabled in libcurl
.
Now I understand that this happends due to my double quote. However, if I remove if, I get the Id is not recognized as an internal or external command, operable program or batch file
, which makes sense because the &
simple means doing another command in cmd
.
So what are my options for executing such download command and extract.
The command itself run fine on cmd
.
答案1
得分: 2
我发现最好不要尝试将多个命令合并到一个执行中。下面的代码完全正常工作,你不必担心转义和可移植性问题,而且还能获得更好的错误处理。
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)
}
}
英文:
I find it best to not try and combine multiple commands in one execution. The below works just fine and you don't have to worry about escaping and portability, you also get better error handling.
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)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论