如何阻止 Golang 在执行 Windows 命令时用反斜杠替换双引号?

How to stop Golang from replacing double-quotes with backslashes when executing a Windows command?

我正在用 Golang 编写一个程序,它将使用 Mozilla 的 Thunderbird 电子邮件客户端发送电子邮件。应该执行的Windows命令是:

 start "" "C:\Program Files (x86)\Mozilla Thunderbird\thunderbird.exe" -compose "to='CloudCoin@Protonmail.com',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. 

如果我将代码更改为这个(移动单词开始):

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