英文:
exec with double quoted argument
问题
我想使用exec
包执行find
Windows命令,但是Windows系统会进行一些奇怪的转义。
我有以下代码:
out, err := exec.Command("find", `"SomeText"`).Output()
但是这会抛出错误,因为Windows会将其转换为
find /SomeText"
有人知道为什么吗?我该如何使用exec包在Windows上执行find
命令?
谢谢!
英文:
I want to execute find
Windows command using exec
package, but windows is doing some weird escaping.
I have something like:
out, err := exec.Command("find", `"SomeText"`).Output()
but this is throwing error because Windows is converting this to
find /SomeText"
Does anyone know why? How I can execute find
on windows using exec package?
Thanks!
答案1
得分: 7
好的,以下是翻译好的内容:
package main
import (
"fmt"
"os/exec"
"syscall"
)
func main() {
cmd := exec.Command(`find`)
cmd.SysProcAttr = &syscall.SysProcAttr{}
cmd.SysProcAttr.CmdLine = `find "SomeText" test.txt`
out, err := cmd.Output()
fmt.Printf("%s\n", out)
fmt.Printf("%v\n", err)
}
很不幸,尽管在2011年添加了对此的支持,但它似乎还没有出现在文档中。(也许我只是不知道在哪里找。)
<details>
<summary>英文:</summary>
OK, it's a bit more complicated than you might have expected, but there *is* a solution:
package main
import (
"fmt"
"os/exec"
"syscall"
)
func main() {
cmd := exec.Command(`find`)
cmd.SysProcAttr = &syscall.SysProcAttr{}
cmd.SysProcAttr.CmdLine = `find "SomeText" test.txt`
out, err := cmd.Output()
fmt.Printf("%s\n", out)
fmt.Printf("%v\n", err)
}
Unfortunately, [although support for this was added in 2011][1], it doesn't appear to have made it into [the documentation][2] yet. (Although perhaps I just don't know where to look.)
[1]: https://github.com/golang/go/issues/1849
[2]: http://golang.org/pkg/os/exec/
</details>
# 答案2
**得分**: 0
FYI,运行:
```go
package main
import (
"fmt"
"os/exec"
)
func main() {
cmd := exec.Command("find", `"SomeText"`)
fmt.Printf("Path: %q, args[1]: %q\n", cmd.Path, cmd.Args[1])
}
在Unix系统上运行结果为:
Path: "/usr/bin/find", args[1]: "\"SomeText\""
在编译为Windows并在Win7上运行的结果为:
Path: "C:\\Windows\\system32\\find.exe", args[1]: "\"SomeText\""
两者看起来都是正确的。
在Windows交叉编译中添加out, err := cmd.Output()
,对于fmt.Printf("%#v\n%v\n", err, err)
,输出如下:
&exec.ExitError{ProcessState:(*os.ProcessState)(0xc0820046a0)}
exit status 1
但我想这只是因为find未能找到任何内容。
英文:
FYI, running:
package main
import (
"fmt"
"os/exec"
)
func main() {
cmd := exec.Command("find", `"SomeText"`)
fmt.Printf("Path: %q, args[1]: %q\n", cmd.Path, cmd.Args[1])
}
On unix gives:
Path: "/usr/bin/find", args[1]: "\"SomeText\""
And cross compiled to Windows and run on Win7 gives:
Path: "C:\\Windows\\system32\\find.exe", args[1]: "\"SomeText\""
Both look correct to me.
Adding out, err := cmd.Output()
to the Windows cross-compile gives the following for fmt.Printf("%#v\%v\n", err, err)
:
&exec.ExitError{ProcessState:(*os.ProcessState)(0xc0820046a0)}
exit status 1
But I imagine that's just because find fails to find anything.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论