Trying to avoid that my PC needs to shutdown while running CPU demanding programs. What I'm doing wrong?

102 Views Asked by At

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)

1

There are 1 best solutions below

2
paxdiablo On

When I run your code, I get:

No se pudo obtener la temperatura.

The most likely reason for that is because temperature is not one of the items available, assuming you're using py-cpuinfo as 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:

import cpuinfo, pprint
pprint.pprint(cpuinfo.get_cpu_info())

On my system, for example, I get:

{'arch': 'X86_64',
 'arch_string_raw': 'x86_64',
 'bits': 64,
 'brand_raw': 'Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz',
 'count': 2,
 'cpuinfo_version': [9, 0, 0],
 'cpuinfo_version_string': '9.0.0',
 'family': 6,
 'flags': ['3dnowprefetch',
           'abm',
           'adx',
           'aes',
           'apic',
           ... lots of irrelevant stuff removed.
           'xsaves',
           'xtopology'],
 'hz_actual': [2592007000, 0],
 'hz_actual_friendly': '2.5920 GHz',
 'hz_advertised': [2600000000, 0],
 'hz_advertised_friendly': '2.6000 GHz',
 'l1_data_cache_size': 65536,
 'l1_instruction_cache_size': 65536,
 'l2_cache_associativity': 6,
 'l2_cache_line_size': 256,
 'l2_cache_size': 524288,
 'l3_cache_size': 12582912,
 'model': 158,
 'python_version': '3.8.10.final.0 (64 bit)',
 'stepping': 10,
 'vendor_id_raw': 'GenuineIntel'}

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 wmic on Windows, or locate the correct /proc or /sys files under Linux.

And, just as an aside, if your machine is shutting down due to overheating, you should probably focus on fixing the root cause of that (the overheating) rather than trying to live with it by reacting to warnings.

The cheapest solution is probably to invest in a compressed air can, opening up the case, and clearing out accumulated dust/gunk from fans (CPU and case) and the case ventilation points. Or, better yet, blast that air everywhere in the case to clear it out.

If that still doesn't fix it, you may want to look into a better case or more grunty fans. Or just more fans in general.

I realise they're not programming solutions but, to be honest, your machine probably shouldn't be shutting down due to overheating. Most modern hardware will simply throttle the CPU until it cools down a little. Better to run slow than not run at all.