程序开发 · 2023年11月27日

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

当前位置: > > > > 在命令提示符下执行时如何处理带引号和不带引号的字符串?

来源:stackoverflow
2024-05-01 08:45:40
0浏览
收藏

学习Golang要努力,但是不要急!今天的这篇文章《在命令提示符下执行时如何处理带引号和不带引号的字符串?》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!

问题内容

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\n不可运行的程序或批处理文件。\r\n”

“c:\program files (x86)\7-zip\7z.exe” x c:\temp\test.zip -oc:\temp\test – 我必须运行此命令在命令提示符下,但它只是执行突出显示的部分

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

正确答案

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 line

proc.stderr = &stderr
proc.stdout = &buf
proc.start()
time.sleep(5 * time.second)
fmt.println("doneee", buf.string(), "error is ", stderr.string())

您可以使用原始字符串。查看。

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

以上就是《在命令提示符下执行时如何处理带引号和不带引号的字符串?》的详细内容,更多关于的资料请关注公众号!