doushijia5684 2016-03-21 06: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-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).

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

报告相同问题?

悬赏问题

  • ¥15 Stata链式中介效应代码修改
  • ¥15 latex投稿显示click download
  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错