簡體   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