【问题标题】:How to get system information in Go?如何在 Go 中获取系统信息?
【发布时间】:2015-05-07 06:42:08
【问题描述】:

谁能推荐一个可以用来获取系统信息的模块,比如Python的psutil

当我尝试>go get github.com/golang/sys get 'sys' 时,我收到了以下信息:

Report Error:
package github.com/golang/sys
        imports github.com/golang/sys
        imports github.com/golang/sys: no buildable Go source files in D:\go_source\src\github.com\golang\sys

这是我的系统环境:

# native compiler windows amd64

GOROOT=D:\Go
#GOBIN=
GOARCH=amd64
GOOS=windows
CGO_ENABLED=1

PATH=c:\mingw64\bin;%GOROOT%\bin;%PATH%

LITEIDE_GDB=gdb64
LITEIDE_MAKE=mingw32-make
LITEIDE_TERM=%COMSPEC%
LITEIDE_TERMARGS=
LITEIDE_EXEC=%COMSPEC%
LITEIDE_EXECOPT=/C

【问题讨论】:

  • 你可以试试go get golang.org/x/sys/windows吗?我已经更新了答案。

标签: go


【解决方案1】:

这是一个简单的 Windows 示例,用于提取主机名、平台、CPU 型号、总 RAM 和磁盘容量。首先安装模块:

go get github.com/shirou/gopsutil 

我在安装时遇到了问题,我也不得不安装:

go get github.com/StackExchange/wmi

现在运行这段代码:

package main

import (
    "fmt"

    "github.com/shirou/gopsutil/cpu"
    "github.com/shirou/gopsutil/disk"
    "github.com/shirou/gopsutil/host"
    "github.com/shirou/gopsutil/mem"
)

// SysInfo saves the basic system information
type SysInfo struct {
    Hostname string `bson:hostname`
    Platform string `bson:platform`
    CPU      string `bson:cpu`
    RAM      uint64 `bson:ram`
    Disk     uint64 `bson:disk`
}

func main() {
    hostStat, _ := host.Info()
    cpuStat, _ := cpu.Info()
    vmStat, _ := mem.VirtualMemory()
    diskStat, _ := disk.Usage("\\") // If you're in Unix change this "\\" for "/"

    info := new(SysInfo)

    info.Hostname = hostStat.Hostname
    info.Platform = hostStat.Platform
    info.CPU = cpuStat[0].ModelName
    info.RAM = vmStat.Total / 1024 / 1024
    info.Disk = diskStat.Total / 1024 / 1024

    fmt.Printf("%+v\n", info)

}

【讨论】:

    【解决方案2】:

    我知道这是一篇旧帖子,但将其发布给其他可以受益的人。

    正是您在此处寻找的内容:

    https://github.com/shirou/gopsutil

    【讨论】:

      【解决方案3】:

      您实际上需要这样做 (following godoc):

      go get golang.org/x/sys/unix
      # or
      go get golang.org/x/sys/windows
      # or
      go get golang.org/x/sys/plan9
      

      (取决于您的操作系统)

      【讨论】:

      • golang.org/x 反映了新组织 (stackoverflow.com/a/26773479/6309)
      • go get golang.org/x/sys...(省略号)似乎在我的机器上工作
      • @Uvelichitel 是的,但你真的需要这三个吗?
      猜你喜欢
      • 2016-03-12
      • 2011-06-02
      • 2011-03-28
      • 2011-12-14
      • 2018-06-07
      • 2014-06-12
      • 2012-05-07
      • 2011-03-07
      • 2016-04-18
      相关资源
      最近更新 更多