[Python] Trying to get the CPU temperature using several libraries returns wrong results

Discussão em 'Python' iniciado por Stack, Maio 1, 2025.

  1. Stack

    Stack Membro Participativo

    I want to get the CPU temperature using Python code. I’m using Windows 11 24H2 and Python 3.10.6. I’ve already tried using WinTmp.CPU_Temp():

    import WinTmp
    print(WinTmp.CPU_Temp())
    >>> 0.0


    But that seems wrong.

    I've also tried:

    import clr
    from pathlib import Path

    try:
    import pynvml
    except ImportError:
    pynvml = None
    try:
    import win32com.client
    except ImportError:
    win32com = None


    def initialize_hardware_monitor():
    try:
    dll_path = str(Path(__file__).parent / "LibreHardwareMonitorLib.dll")
    if not os.path.exists(dll_path):
    dll_path = str(Path(__file__).parent / "OpenHardwareMonitorLib.dll")
    if not os.path.exists(dll_path):
    print("Error: LibreHardwareMonitorLib.dll or OpenHardwareMonitorLib.dll not found.")
    return None
    clr.AddReference(dll_path)
    from LibreHardwareMonitor import Hardware
    handle = Hardware.Computer()
    handle.IsCpuEnabled = True
    handle.IsGpuEnabled = True
    handle.Open()
    print("Hardware Monitor initialized successfully")
    return handle
    except Exception as e:
    print(f"Error initializing Hardware Monitor: {e}")
    return None


    def get_wmi_msacpi_temperature(sensor_type="cpu"):
    if not win32com:
    print(f"pywin32 not installed for {sensor_type.upper()}")
    return None
    try:
    wmi_obj = win32com.client.GetObject("winmgmts:\\\\.\\root\\wmi")
    sensors = wmi_obj.ExecQuery("SELECT * FROM MSAcpi_ThermalZoneTemperature")
    for sensor in sensors:
    temp_kelvin = sensor.CurrentTemperature / 10.0
    temp_celsius = temp_kelvin - 273.15
    if sensor_type in sensor.InstanceName.lower() and 0 < temp_celsius < 100:
    return round(temp_celsius, 1)
    print(f"No {sensor_type.upper()} temperature sensor in MSAcpi_ThermalZoneTemperature")
    return None
    except Exception as e:
    print(f"Error getting {sensor_type.upper()} temperature via MSAcpi: {e}")
    return None


    def get_cpu_temperature():
    try:
    handle = initialize_hardware_monitor()
    if handle:
    for hardware in handle.Hardware:
    hardware.Update()
    if hardware.HardwareType == 2:
    for sensor in hardware.Sensors:
    if sensor.SensorType == 2 and "cpu" in sensor.Name.lower():
    temp = round(sensor.Value, 1)
    if 0 < temp < 100:
    return temp
    print("No CPU temperature sensor found in Hardware Monitor")
    except Exception as e:
    print(f"Error getting CPU temperature via Hardware Monitor: {e}")

    # WMI
    temp = get_wmi_msacpi_temperature("cpu")
    if temp:
    return temp
    print("All CPU temperature methods failed.")
    return None


    print(get_cpu_temperature())


    Output:

    Hardware Monitor initialized successfully
    No CPU temperature sensor found in Hardware Monitor
    Error getting CPU temperature via MSAcpi: (-2147217405, 'OLE error 0x80041003', None, None)
    All CPU temperature methods failed.
    None


    So, by using WMI or MSAcpi to retrieve the temperature also through OpenHardwareMonitorLib.dll, LibreHardwareMonitorLib.dll, or CPUThermometerLib.dll, I get incorrect information (typically 0°C or 29°C) or errors. My main goal is to implement my idea without running OpenHardwareMonitor (OHM). I can use the DLLs, but I don’t want to run third-party applications. (Btw, the OHM app shows correct data.)

    I also tried all the code from these topics: Accessing CPU temperature in python But nothing works.

    Do you have any ideas on how I can get the information I’m interested in?

    I’m testing my code on a Ryzen 9 3950X and Ryzen 7 2700X.

    (Also, please describe the process of using .dll files in code in more detail, as I don’t have experience in using C#, C++ libraries and in mixing Python code with it, if the solution you suggest includes using C libraries.

    If that's not possible, also tell me so I can look in another direction.)

    Continue reading...

Compartilhe esta Página