防止 Golang 在 Windows 下执行命令时替换双引号为反斜杠
时间:2024-03-24
浏览: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学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
热门专题
