登录
首页 >  Golang >  Go问答

防止 Golang 在 Windows 下执行命令时替换双引号为反斜杠

来源:stackoverflow

时间:2024-03-24 11:33:37 341浏览 收藏

在 Windows 系统中使用 Go 编写程序时,如果执行的命令包含双引号,可能会出现双引号被反斜杠替换的问题。这会导致命令无法正确执行,并出现错误提示。为了解决这个问题,需要对命令字符串进行手动拆分,以便保留双引号。

问题内容

我正在用 golang 编写一个程序,它将使用 mozilla 的 thunderbird 电子邮件客户端发送电子邮件。应执行的 windows 命令是:

start "" "c:\program files (x86)\mozilla thunderbird\thunderbird.exe" -compose "to='[email protected]',subject='subject1',body='hello'" -offline

我的 go 代码如下所示(命令是上面列出的命令):

var command string
    command = `start "" "c:\program files (x86)\mozilla thunderbird\thunderbird.exe"`
    command += ` -compose "to='` + toaddress + `',`
    command += `subject='subject1',`
    command += `body='hello'"`
    command += ` -offline`

    cmd := exec.command("cmd.exe", "/c", command)

但是我收到错误:

windows cannot find '\\'. make sure you typed the name correctly, and then try again.

如果我将代码更改为此(移动单词 start):

var command string
    command = ` "" "c:\program files (x86)\mozilla thunderbird\thunderbird.exe"`
    command += ` -compose "to='` + toaddress + `',`
    command += `subject='subject1',`
    command += `body='hello'"`
    command += ` -offline`

    fmt.println("command: " + command)

    cmd := exec.command("cmd.exe", "/c", "start", command)

然后我收到另一个错误:

Windows cannot find 'Files'. Make sure you typed the name correctly, and then try again.

似乎不是尝试启动“”,而是尝试启动\\。如何保留双引号?


解决方案


您的问题可能是传递给 exec.command 的每个单独字符串都作为单个参数传递(不解析它)给 cmd.exe,它可能也不会分割给定的字符串,因此您必须自己执行此操作。

请参阅 this example,其中参数也被拆分。您应该能够省略 " ,因为无论如何您都手动将其拆分,或者为它编写一个程序或使用执行拆分的解释器运行它。

func do() {
    args := []string{
        "/C",
        "start",
        "",
        `C:\Program Files (x86)\Mozilla Thunderbird\thunderbird.exe`,
        "-compose",
        "to=" + toAddress + ",subject=Subject1,body=Hello",
        "-offline",
    }
    cmd := exec.Command("cmd.exe", args...)
}

以上就是《防止 Golang 在 Windows 下执行命令时替换双引号为反斜杠》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>