Crontab 和 python 脚本写入文件

Crontab and python script writing to file

您好,我 运行正在 Raspberry Pi 在同一个 Pi 上使用 OSMC 和网络服务器。

我制作了一个 python 脚本来获取 cpu 温度、使用情况、内存等。 当我使用以下命令执行脚本时: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 }'").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))

为什么它只将部分数据写入文本文件? 任何帮助深表感谢!

您可以通过编写针对问题的脚本来诊断问题。这将记录从系统调用返回的所有信息。我认为检查错误的 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 }'", file)