Accessing CPU temperature in python

前端 未结 7 1500
暗喜
暗喜 2020-11-29 04:07

I need an example code for accessing CPU temperature in python.

I\'m running windows 7, BTW.

相关标签:
7条回答
  • 2020-11-29 04:31

    Check out the cputemp library.

    EDIT: on windows, you might be able to convert this IronPython script which uses WMI using the python WMI library.

    0 讨论(0)
  • 2020-11-29 04:35

    The code offered by eadmaster may work for older CPUs that OpenHardwareMonitor has been programmed for, but I have a Skylake i7 6700K CPU. OpenHardwareMonitor offered no results for me. However, there is a fork of this program called CPU Thermometer, which is based on OpenHardwareMonitor which does recognize my CPU.

    In chasing down how to get CPU temps via Python, I switched to IronPython in order to have access to the .Net framework and have easy access to other performance data, but it should be fairly easy to figure out how to retro fit it for vanilla Python 2.7 (Just run CPU Thermometer instead ofOpenHardwareMonitor and change your namespace to "root\CPUThermometer"? Could it be that simple?).

    #
    # CPU Temp --REQUIRES CPU TEMPERATURE TO BE RUNNING!--
    #
    import clr
    clr.AddReference('System.Management')
    from System.Management import (ManagementScope, ManagementObject, ManagementObjectSearcher, WqlObjectQuery)
    
    scope = ManagementScope("root\CPUThermometer")
    
    searcher = ManagementObjectSearcher(scope, 
        WqlObjectQuery("SELECT * FROM Sensor Where SensorType LIKE 'Temperature'"), None)
    
    mo = ManagementObject()
    
    print "\n"
    print "              Temp      Min       Max"
    
    strout = str(' ')
    
    for mo in searcher.Get():
        strout = '{0}   {1} C    {2} C    {3} C\n{4}'.format(mo["Name"], mo["Value"], mo["Min"], mo["Max"], strout)
    
    print strout
    

    Sample Output:

    D:\IronPython 2.7>ipy64 c:\users\neamerjell\desktop\test.py
    
    
                  Temp      Min       Max
    CPU Core #1   21.0 C    20.0 C    37.0 C
    CPU Core #2   23.0 C    21.0 C    39.0 C
    CPU Core #3   21.0 C    20.0 C    32.0 C
    CPU Core #4   21.0 C    20.0 C    36.0 C
    

    I found out the hard way that the query is not quite standard SQL and DOES NOT LIKE the "Order By" clause, so I had to do some fancy string formatting to get the order correct as the query returns the cores in reverse order. This baffled me for a bit until I devised this way around it.

    0 讨论(0)
  • 2020-11-29 04:48

    You can use pywin32 to access the native Windows API. I believe it should be possible to query the Windows API for the CPU temperature if the manufacturer for your mainboard driver registers a WMI Data Provider through their driver. Assuming this is the case you could download the pywin32 extensions and the Python WMI module mentioned in the answer by ars, and then proceed as follows:

    import wmi
    w = wmi.WMI()
    print w.Win32_TemperatureProbe()[0].CurrentReading
    

    Looking at the IronPython script in the ars' answer there seems to be another way to do it too, using a different WMI object. Using the same API and approach you could try receiving the temperature value with

    w = wmi.WMI(namespace="root\wmi")
    temperature_info = w.MSAcpi_ThermalZoneTemperature()[0]
    print temperature_info.CurrentTemperature
    

    which apparently should return the temperature value in tenths of Kelvin, thus to receive the degree in Celsius I guess you just divide this value by 10 and subtract ~273.

    0 讨论(0)
  • 2020-11-29 04:48

    I received a C++ project from a 3rd party and found how to get the CPU and Board Temp using C++. I then found this which I used to to help me mimic the C++ functions in python with ctypes, a lot of this code is copied directly from that repository. '\\.\AdvLmDev' is specific to the PC I was using, and should be replaced with '\\.\PhysicalDrive0'. There is also a function to get other CPU power measurements. I did this because I didn't want to use Open Hardware Monitor. You may have to run the code as administrator for it to work.

    import ctypes
    import ctypes.wintypes as wintypes
    from ctypes import windll
    
    
    LPDWORD = ctypes.POINTER(wintypes.DWORD)
    LPOVERLAPPED = wintypes.LPVOID
    LPSECURITY_ATTRIBUTES = wintypes.LPVOID
    
    GENERIC_READ = 0x80000000
    GENERIC_WRITE = 0x40000000
    GENERIC_EXECUTE = 0x20000000
    GENERIC_ALL = 0x10000000
    
    FILE_SHARE_WRITE=0x00000004
    ZERO=0x00000000
    
    CREATE_NEW = 1
    CREATE_ALWAYS = 2
    OPEN_EXISTING = 3
    OPEN_ALWAYS = 4
    TRUNCATE_EXISTING = 5
    
    FILE_ATTRIBUTE_NORMAL = 0x00000080
    
    INVALID_HANDLE_VALUE = -1
    FILE_DEVICE_UNKNOWN=0x00000022
    METHOD_BUFFERED=0
    FUNC=0x900
    FILE_WRITE_ACCESS=0x002
    
    NULL = 0
    FALSE = wintypes.BOOL(0)
    TRUE = wintypes.BOOL(1)
    
    
    def CTL_CODE(DeviceType, Function, Method, Access): return (DeviceType << 16) | (Access << 14) | (Function <<2) | Method
    
    
    
    
    def _CreateFile(filename, access, mode, creation, flags):
        """See: CreateFile function http://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).asp """
        CreateFile_Fn = windll.kernel32.CreateFileW
        CreateFile_Fn.argtypes = [
                wintypes.LPWSTR,                    # _In_          LPCTSTR lpFileName
                wintypes.DWORD,                     # _In_          DWORD dwDesiredAccess
                wintypes.DWORD,                     # _In_          DWORD dwShareMode
                LPSECURITY_ATTRIBUTES,              # _In_opt_      LPSECURITY_ATTRIBUTES lpSecurityAttributes
                wintypes.DWORD,                     # _In_          DWORD dwCreationDisposition
                wintypes.DWORD,                     # _In_          DWORD dwFlagsAndAttributes
                wintypes.HANDLE]                    # _In_opt_      HANDLE hTemplateFile
        CreateFile_Fn.restype = wintypes.HANDLE
    
        return wintypes.HANDLE(CreateFile_Fn(filename,
                             access,
                             mode,
                             NULL,
                             creation,
                             flags,
                             NULL))
    
    
    handle=_CreateFile('\\\\.\\AdvLmDev',GENERIC_WRITE,FILE_SHARE_WRITE,OPEN_EXISTING,ZERO)
    
    def _DeviceIoControl(devhandle, ioctl, inbuf, inbufsiz, outbuf, outbufsiz):
        """See: DeviceIoControl function
    http://msdn.microsoft.com/en-us/library/aa363216(v=vs.85).aspx
    """
        DeviceIoControl_Fn = windll.kernel32.DeviceIoControl
        DeviceIoControl_Fn.argtypes = [
                wintypes.HANDLE,                    # _In_          HANDLE hDevice
                wintypes.DWORD,                     # _In_          DWORD dwIoControlCode
                wintypes.LPVOID,                    # _In_opt_      LPVOID lpInBuffer
                wintypes.DWORD,                     # _In_          DWORD nInBufferSize
                wintypes.LPVOID,                    # _Out_opt_     LPVOID lpOutBuffer
                wintypes.DWORD,                     # _In_          DWORD nOutBufferSize
                LPDWORD,                            # _Out_opt_     LPDWORD lpBytesReturned
                LPOVERLAPPED]                       # _Inout_opt_   LPOVERLAPPED lpOverlapped
        DeviceIoControl_Fn.restype = wintypes.BOOL
    
        # allocate a DWORD, and take its reference
        dwBytesReturned = wintypes.DWORD(0)
        lpBytesReturned = ctypes.byref(dwBytesReturned)
    
        status = DeviceIoControl_Fn(devhandle,
                      ioctl,
                      inbuf,
                      inbufsiz,
                      outbuf,
                      outbufsiz,
                      lpBytesReturned,
                      NULL)
    
        return status, dwBytesReturned
    
    class OUTPUT_temp(ctypes.Structure):
            """See: http://msdn.microsoft.com/en-us/library/aa363972(v=vs.85).aspx"""
            _fields_ = [
                    ('Board Temp', wintypes.DWORD),
                    ('CPU Temp', wintypes.DWORD),
                    ('Board Temp2', wintypes.DWORD),
                    ('temp4', wintypes.DWORD),
                    ('temp5', wintypes.DWORD)
                    ]
    
    class OUTPUT_volt(ctypes.Structure):
            """See: http://msdn.microsoft.com/en-us/library/aa363972(v=vs.85).aspx"""
            _fields_ = [
                    ('VCore', wintypes.DWORD),
                    ('V(in2)', wintypes.DWORD),
                    ('3.3V', wintypes.DWORD),
                    ('5.0V', wintypes.DWORD),
                    ('temp5', wintypes.DWORD)
                    ]
    
    def get_temperature():
        FUNC=0x900
        outDict={}
    
        ioclt=CTL_CODE(FILE_DEVICE_UNKNOWN, FUNC, METHOD_BUFFERED, FILE_WRITE_ACCESS)
    
        handle=_CreateFile('\\\\.\\AdvLmDev',GENERIC_WRITE,FILE_SHARE_WRITE,OPEN_EXISTING,ZERO)
    
        win_list = OUTPUT_temp()
        p_win_list = ctypes.pointer(win_list)
        SIZE=ctypes.sizeof(OUTPUT_temp)
    
    
        status, output = _DeviceIoControl(handle, ioclt , NULL, ZERO, p_win_list, SIZE)
    
    
        for field, typ in win_list._fields_:
                    #print ('%s=%d' % (field, getattr(disk_geometry, field)))
                    outDict[field]=getattr(win_list,field)
        return outDict
    
    def get_voltages():
        FUNC=0x901
        outDict={}
    
        ioclt=CTL_CODE(FILE_DEVICE_UNKNOWN, FUNC, METHOD_BUFFERED, FILE_WRITE_ACCESS)
    
        handle=_CreateFile('\\\\.\\AdvLmDev',GENERIC_WRITE,FILE_SHARE_WRITE,OPEN_EXISTING,ZERO)
    
        win_list = OUTPUT_volt()
        p_win_list = ctypes.pointer(win_list)
        SIZE=ctypes.sizeof(OUTPUT_volt)
    
    
        status, output = _DeviceIoControl(handle, ioclt , NULL, ZERO, p_win_list, SIZE)
    
    
        for field, typ in win_list._fields_:
                    #print ('%s=%d' % (field, getattr(disk_geometry, field)))
                    outDict[field]=getattr(win_list,field)
        return outDict
    
    0 讨论(0)
  • 2020-11-29 04:49

    Use the WMI module + Open Hardware Monitor + its WMI interface described here.

    Sample code:

    import wmi
    w = wmi.WMI(namespace="root\OpenHardwareMonitor")
    temperature_infos = w.Sensor()
    for sensor in temperature_infos:
        if sensor.SensorType==u'Temperature':
            print(sensor.Name)
            print(sensor.Value)
    
    0 讨论(0)
  • 2020-11-29 04:51

    I have used the utility from https://github.com/BennyCarbajal/PyTherm

    Pretty much install pythonnet with:

    pip install pythonnet
    

    Then just execute the terminal as administrator and finally execute the file:

    python pytherm.py
    

    It also works if you run it as a regular user but will not output as much data.

    Since it returns the data in JSON format, it should be easy for you to just get the data of the specific hardware you are looking for.

    0 讨论(0)
提交回复
热议问题