在使用os/exec和在命令行执行时出现了无法解释的不同结果。

huangapple go评论79阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年1月15日 18:53:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75124507.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定