英文:
Error in executing a command in golang
问题
我尝试在Golang中获取操作系统名称,以下是我的代码。
// GetOsName.go
package main
import (
"fmt"
"os/exec"
)
func main() {
fmt.Println("systeminfo", "|", "findstr", "/B", "/C:\"OS Name\"")
Out, err := exec.Command("systeminfo", "|", "findstr", "/B", "/C:\"OS Name\"").Output()
if err != nil {
fmt.Println("Err:", err)
} else {
fmt.Println("Out:", string(Out))
}
}
但是当我执行代码时,我得到了这个消息:
systeminfo | findstr /B /C:"OS Name"
Err: exit status 1
命令是正确的。当我尝试单独执行命令时,它正常工作。请帮助我解决这个问题,提前感谢。
英文:
I tried to get the OS name in Golang The below is my code.
// GetOsName.go
package main
import (
"fmt"
"os/exec"
)
func main() {
fmt.Println("systeminfo","|","findstr","/B","/C:\"OS Name\"")
Out,err:=exec.Command("systeminfo","|","findstr","/B","/C:\"OS Name\"").Output()
if err!=nil{
fmt.Println("Err:",err)
}else{
fmt.Println("Out:",string(Out))
}
}
But when i execute the code i get this message
systeminfo | findstr /B /C:"OS Name"
Err: exit status 1
The command is right. When i try to execute the command in separate it works fine.
Help me to solve this Thanks in Advance.
答案1
得分: 1
你的命令是不正确的。你的命令是shell代码,除了shell(这里是cmd.exe)之外无法执行。如果你真的想要像这样获取操作系统的名称:请使用cmd.exe执行你的命令作为参数。你可以考虑在Go语言中执行systeminfo.exe并解析输出(而不是使用shell)。
英文:
Your command is not right. Your command is shell code and cannot be executed except by a shell (here cmd.exe). If you really want to get the OS name like this: Execute cmd.exe with your command as an argument. You might consider executing systeminfo.exe and parsing the output in Go (instead of the shell).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论