在执行Go语言命令时出现错误。

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

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).

huangapple
  • 本文由 发表于 2016年3月21日 14:59:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/36124855.html
匿名

发表评论

匿名网友

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

确定