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

huangapple go评论83阅读模式
英文:

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)
	}
}

huangapple
  • 本文由 发表于 2021年12月15日 03:02:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/70354299.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定