doushijia5684 2016-03-20 22:59
浏览 330
已采纳

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

  • 写回答

1条回答 默认 最新

  • dqb78642 2016-03-20 23: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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部