Search code examples
pythonraspberry-picronstartup

Crontab and python script writing to file


Hi im running a Raspberry Pi using OSMC and a webserver on the same Pi.

Ive made a python script which gets the cpu temp, usage, memory etc. When i execute the script using: sudo python state.py it works, it gets the values and writes them to a txt file.

I want the script to run on startup so i made a crontab:

@reboot sudo python /home/osmc/python/state.py &

This works, however it dosent write the CPU stats to the file, only memory and disk stats.

My python script looks like this:

#!/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))

Is there any reason why it only write some of the data to the text file? Any help is much appreciated!


Solution

  • You can diagnose the problem by writing a script focused on the problem. This one will record all of the info coming back from the system calls. I think that a modified version of my_popen that checks for errors... or one of the error checking calls in subprocess is a good idea. I do a lot of system calls myself and have a complex wrapper for Popen that logs and does all sorts of fancy stuff. Run this script the same way as your regular one and see what happens:

    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)