When using Raspberry Pi 4, the CPU gets quite hot. I wanted to find out how hot the CPU was, so I made a program using Python3 to display the CPU temperature every 5 seconds.
OS : Ubuntu server20.04 + Xubuntu Desktop(gdm3)
cpu_temperature.py
import time
import threading
import subprocess
def schedule(interval, func, wait = True):
base_time = time.time()
next_time = 0
while True:
t = threading.Thread(target = func)
t.start()
if wait:
t.join()
next_time = ((base_time - time.time()) % interval) or interval
time.sleep(next_time)
def get_cpu_temperature():
output = subprocess.check_output("cat /sys/class/thermal/thermal_zone0/temp", shell = True, encording = "UTF-8")
return int(output) / 1000
def print_cpu_temperature():
print(get_cpu_temperature())
if __name__ == "__main__":
schedule(5, print_cpu_temperature)
I referred to the following article. Execute processing in Python at regular intervals It is a plagiarism of the schedule function introduced in the article. You can specify how many seconds you want to execute with interval and which function you want to execute with func. For details, please refer to the article at the URL.
I referred to the following article. I tried to get the CPU temperature of Raspberry Pi (Raspbian) without using cat Execute command from Python It seems that the CPU temperature can be obtained by using vcgencmd, but this time I decided to use cat instead of that method. If you use cat, it will be output at 1000 times the value, so it is difficult to understand if you display it as it is.
There are various ways to call Linux commands from Python3, but this time I wanted to process the string obtained using cat in Python, so I decided to use the check_output function.
Use cat in the check_output function to get the CPU temperature. Since the value is multiplied by 1000 as it is, I changed the character string to an int type and divided it by 1000 to make it return. If you use vcgencmd, you can return it as it is.
It is a function that only prints the value obtained by the get_cput_temperature function. Originally I tried to draw a graph using the schedule function and get_cpu_temperature function, but before that, I had a problem if the above two functions did not work properly, so I made this function.
It means to execute the print_cpu_temperature function every 5 seconds. If you change the 5 part to 10, the interval will be 10 seconds.
Recommended Posts