英文:
Inexplicably different results between using os/exec and executing at the command line
问题
我写了一个使用Golang中的os/exec包运行命令的程序。
import (
	"fmt"
	"os/exec"
)
func main() {
	cmd := exec.Command("taskkill", "/f /im VInTGui.exe")
	err := cmd.Run()
	if err != nil {
		fmt.Printf("err: %v\n", err)
	}
}
当我运行这个程序时,它打印出:err: exit status 1
但是当我在Windows命令行中直接运行命令taskkill /f /im VInTGui.exe时,它成功了。
为什么使用os/exec包运行命令和直接在Windows命令行中运行命令(使用相同的用户和权限)会有不同的结果?我该如何修复我的程序?
英文:
I write a program which run a command use package os/exec in Golang.
import (
	"fmt"
	"os/exec"
)
func main() {
	cmd := exec.Command("taskkill", "/f /im VInTGui.exe")
	err := cmd.Run()
	if err != nil {
		fmt.Printf("err: %v\n", err)
	}
}
When I run that program , it printed: err: exit status 1
But when I run command taskkill /f /im VInTGui.exe in Windows Command Line. It success.
Why run command by package os/exec and run command directly by Windows Command Line (using same user same permissions) has Different result? How can I fix my program?
答案1
得分: 4
解决方法是使用Command对象的Stderr属性。可以像这样操作:
cmd := exec.Command("taskkill", "/f", "/im", "VInTGui.exe")
var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
    fmt.Printf("%v: %s\n", err, stderr.String())
    return
}
fmt.Println("Result: " + out.String())
在你的情况下,只需将
exec.Command("taskkill", "/f /im VInTGui.exe")
改为
exec.Command("taskkill", "/f", "/im", "VInTGui.exe")
不要将所有参数合并为一个字符串。
英文:
The solution is to use the Stderr property of the Command object. This can be done like this:
cmd := exec.Command("taskkill", "/f /im VInTGui.exe")
var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
    fmt.Printf("%v: %s\n", err, stderr.String())
    return
}
fmt.Println("Result: " + out.String())
In your case, just change
exec.Command("taskkill", "/f /im VInTGui.exe")
to
exec.Command("taskkill", "/f", "/im",  "VInTGui.exe")
Don't merge all arguments to one string.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论