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

执行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 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 github训练的模型参数无法下载
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案
  • ¥50 winform中使用edge的Kiosk模式
  • ¥15 关于#python#的问题:功能监听网页