doushijia5684
2016-03-21 06:59
浏览 308
已采纳

在Golang中执行命令时出错

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.

图片转代码服务由CSDN问答提供 功能建议

我试图在Golang中获取操作系统名称。这是我的代码。 < pre> // 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 \”“)。如果err!= nil { fmt.Println(” Err:“,err) } else { fmt。 Println(“ Out:”,string(Out)) } }

但是当我执行代码时,我会收到此消息 \ n

  systeminfo |  findstr / B / C:“操作系统名称” 
Err:退出状态1 
   
 
 

该命令正确。 当我尝试单独执行命令时,效果很好。 请帮助我提前解决此问题。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dqb78642 2016-03-21 07:05
    已采纳

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

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题