My computer has an automatic protection system that prevents it from overheating, so when it reaches a certain temperature it protects itself by shutting down. I like this because I made a significant investment in my computer. However, I would like to find out before these thermal events happen. To be able to save my work. In a first phase, I am trying to get the temperature and then my plan is to set an audible alarm in "yellow".
However, I haven't managed to get my CPU temperature yet. What am I doing wrong?
Following is my current code:
import cpuinfo
from colorama import Fore, Back, Style, init
# Inicializar colorama
init(autoreset=True)
# Función para obtener la temperatura de la CPU
def get_cpu_temperature():
try:
info = cpuinfo.get_cpu_info()
temperature = info.get('temperature', None)
return temperature
except Exception as e:
return f"{Fore.CYAN}Error al obtener temperatura: {e}"
# Función para mostrar la temperatura con colores
def display_temperature(temperature):
if temperature is None:
print(f"{Fore.CYAN}No se pudo obtener la temperatura.")
else:
temp_str = f"Temperatura: {temperature}°C"
if temperature < 40:
print(f"{Fore.GREEN}{temp_str}")
elif temperature < 70:
print(f"{Fore.YELLOW}{temp_str}")
else:
print(f"{Fore.RED}¡ALERTA! {temp_str}")
# Obtener la temperatura de la CPU
temperature = get_cpu_temperature()
# Mostrar la temperatura o el mensaje de error con colores
display_temperature(temperature)
When I run your code, I get:
The most likely reason for that is because temperature is not one of the items available, assuming you're using
py-cpuinfoas I am. The available items are shown here (see under "Fields" heading).I suggest you run the following code to figure out what it returns for you:
On my system, for example, I get:
In terms of how to rectify this situation, you'll probably need to specify your environment as accessing temperatures is not necessarily something that's easy to do cross-platform. For example, you would probably use
wmicon Windows, or locate the correct/procor/sysfiles under Linux.