2

我喜欢获取我的 Pi 的系统信息,例如 CPU 使用率、CPU 温度、RAM 使用率、正常运行时间和可用磁盘大小。我知道如何在 Python 中做到这一点,但它不会在 Ruby 中工作。有人可以告诉我如何实现这一目标吗?我认为它一定是 Ruby,因为我的 Siriproxy 需要它,并且插件是用 Ruby 编写的。

坦克优势!

这是 Python 脚本:

#!/usr/bin/env python

import os, time


# Return CPU temperature as a character string
def getCPUtemperature():
    res = os.popen('vcgencmd measure_temp').readline()
    return(res.replace("temp=","").replace("'C\n",""))

# Return RAM information (unit=kb) in a list
# Index 0: total RAM
# Index 1: used RAM
# Index 2: free RAM
def getRAMinfo():
    p = os.popen('free')
    i = 0
    while 1:
        i = i + 1
        line = p.readline()
        if i==2:
            return(line.split()[1:4])

# Return % of CPU used by user as a character string
def getCPUuse():
    return(str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip(\
               )))

# Return information about disk space as a list (unit included)
# Index 0: total disk space
# Index 1: used disk space
# Index 2: remaining disk space
# Index 3: percentage of disk used
def getDiskSpace():
    p = os.popen("df -h /")
    i = 0
    while 1:
        i = i +1
        line = p.readline()
        if i==2:
            return(line.split()[1:5])

# CPU informatiom
CPU_temp = getCPUtemperature()
CPU_usage = getCPUuse()

# RAM information
# Output is in kb, here I convert it in Mb for readability
RAM_stats = getRAMinfo()
RAM_total = round(int(RAM_stats[0]) / 1000,1)
RAM_used = round(int(RAM_stats[1]) / 1000,1)
RAM_free = round(int(RAM_stats[2]) / 1000,1)

# Disk information
DISK_stats = getDiskSpace()
DISK_total = DISK_stats[0]
DISK_free = DISK_stats[1]
DISK_perc = DISK_stats[3]
4

1 回答 1

3

这些方法定义应该对您有所帮助。我无法测试它们,但如果没有发现它们应该非常接近。

def get_cpu_temperature
  %x{vcgencmd measure_temp}.lines.first.sub(/temp=/, '').sub(/C\n/, '')
end

def get_ram_info
  %x{free}.lines.to_a[1].split[1,3]
end

def get_cpu_use
  %x{top -n1}.lines.find{ |line| /Cpu\(s\):/.match(line) }.split[1]
end

def get_disk_Space
    %x{df -h /}.lines.to_a[1].split[1,4]
end
于 2013-06-05T16:54:03.067 回答