我正在使用OSMC和同一Pi上的网络服务器运行Raspberry Pi。
我做了一个python脚本,它获取了cpu temp,usage,memory等。
当我使用sudo python state.py
执行脚本时,它可以工作,它获取值并将它们写入txt文件。
我希望脚本在启动时运行,所以我创建了一个crontab:
@reboot sudo python /home/osmc/python/state.py &
这样可行,但它会将CPU统计信息写入文件,只写入内存和磁盘统计信息。
我的python脚本如下所示:
#!/usr/bin/python
import os
import sys
import commands
import 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])
while True:
# 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]
starttime = time.time()
file = open("/var/www/html/rspi_state.txt", "w")
file.write(CPU_temp + "\n")
file.write(CPU_usage + "\n")
file.write(DISK_stats[1] + "\n")
file.write(DISK_stats[0] + "\n")
file.write(DISK_stats[3] + "\n")
file.write(str(RAM_total) + "\n")
file.write(str(RAM_free) + "\n")
file.close()
print "CPU TEMP: " + CPU_temp
time.sleep(9.0 - ((time.time() - starttime) % 9.0))
有什么理由说它只将一些数据写入文本文件? 任何帮助深表感谢!
答案 0 :(得分:0)
您可以通过编写专注于问题的脚本来诊断问题。这个将记录从系统调用返回的所有信息。我认为my_popen
的修改版本会检查错误......或subprocess
中的错误检查调用之一是个好主意。我自己做了很多系统调用,并为Popen提供了一个复杂的包装器,可以记录并执行各种奇特的操作。以与常规脚本相同的方式运行此脚本,看看会发生什么:
import subprocess as subp
def my_popen(cmd, file):
file.write('cmd: {}\n'.format(cmd))
proc = subp.Popen(cmd, shell=True, stdout=subp.PIPE, stderr=subp.PIPE)
out, err = proc.communicate()
print('return code: {}\n'.format(proc.returncode))
print('out: {}\n'.format(out))
print('err: {}\n'.format(err))
print('------\n')
return out
with file = open("/var/www/html/test_state.txt", "w") as file:
my_popen('vcgencmd measure_temp', file)
my_popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'", file)