在命令提示符下执行时如何处理带引号和不带引号的字符串?

input comes from an JSON request which looks like


   "inputString" : "\"C:\\Program Files (x86)\\7-Zip\\7z.exe\" x c:\\temp\\test.zip -oc:\\temp\\test" 

}


package main


import (

    "fmt"

    "os/exec"

)


func main() {

    //Input received will be of this format

    var inputstring string = "\"C:\Program Files (x86)\7-Zip\7z.exe\" x c:\temp\firmware8.zip -oc:\temp\fw"


    cmd := exec.Command("cmd", "/c", inputstring)


    out, err := cmd.Output()


    fmt.Println("doneee", string(out), "err", err)

}

输出 : "'\"C:\Program Files (x86)\7-Zip\7z.exe\

"'未被识别为内部或外部命令,\r\不可运行的程序或批处理文件。\r\n"


"C:\Program Files (x86)\7-Zip\7z.exe" xc:\temp\test.zip -oc:\temp\test - 我必须在命令提示符下运行此命令,但它只是在执行部分突出显示


由于输入字符串不是静态的(它来自 JSON),所以我们不能将它们拆分为参数


互换的青春
浏览 120回答 2
2回答

慕丝7291255

您可以使用原始字符串。看看这个教程。var inputstring string = `"C:\Program Files (x86)\7-Zip\7z.exe" x c:\temp\test.zip -oc:\temp\test`

摇曳的蔷薇

var inputstring string = "\"C:\\Program Files (x86)\\7-Zip\\7z.exe\" x c:\\temp\\firmware8.zip -oc:\\temp\\fw"var buf, stderr bytes.Buffer*proc := exec.Command("cmd")proc.SysProcAttr = &syscall.SysProcAttr{CmdLine: fmt.Sprintf(`/c "%s"`, inputstring)}* //Adding this line helped to add the cmd as single lineproc.Stderr = &stderrproc.Stdout = &bufproc.Start()time.Sleep(5 * time.Second)fmt.Println("doneee", buf.String(), "error is ", stderr.String())
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go