duanbairan4235 2019-07-27 05:24
浏览 986
已采纳

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

I am writing a program in Golang that will use Mozilla's Thunderbird email client to send email. The Windows command that should be executed is:

 start "" "C:\Program Files (x86)\Mozilla Thunderbird\thunderbird.exe" -compose "to='CloudCoin@Protonmail.com',subject='Subject1',body='Hello'" -offline

My Go code looks like this (command is the one listed above) :

    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)

But I get an error:

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

If I change the code to this (moving the word 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)

Then I get another error:

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

It seems that instead of trying to start "" it is trying to start \\. How can I keep my double-quotes?

  • 写回答

1条回答 默认 最新

  • douniao7308 2019-07-27 09:09
    关注

    Your problem likely is that every separate string passed to exec.Command is passed on (without parsing it) as a single argument to cmd.exe, which does probably not split given strings either, so you have to do it yourself.

    See this example where the argument is being split up too. You should be able to leave " out since you split it up manually anyway, or write a program for it or run it with an interpreter which does the splitting.

    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...)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable