- How to directly get CPU temp in Python?
- 8 Answers 8
- Температура CPU, GPU, RAM, с помощью Python
- Как узнать температуру ЦП в Python 3.8?
- 1 ответ 1
- Saved searches
- Use saved searches to filter your results more quickly
- Ayilay/CPUTempMonitor
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
How to directly get CPU temp in Python?
Goal is to switch an exhaust fan at an outside data-logging station at a solar power station. The data-collection program is written in Python under Raspbian. For reading CPU temp at a command line, there is the vcgencmd command. Example in bash:
echo "The CPU is at $(vcgencmd measure_temp) degrees." The CPU is at temp=39.2'C degrees.
as the command returns the string «temp=39.2’C» I’ve never personally seen this fail, although I know there is a question about that point. vcgencmd measure_temp doesn’t always work Meanwhile, I would like to obtain the CPU temp in Python. Back to the Goal: the fans are controlled by PiGPIO calls, and during data-logging I keep my external system calls to the minimum (ie., there aren’t any other than Python file I/O). Also, it would be much preferable to get the answer as a simple floating-point value than to extract it from a return strung. The question is: How to directly get CPU temp in Python?
8 Answers 8
For those coming here from Google. You can get Raspberry CPU temp in Python using gpiozero package.
from gpiozero import CPUTemperature cpu = CPUTemperature() print(cpu.temperature)
It has already been answered and accepted but I see that no one has brought up this alternative that doesn’t depend on running a command but rather on reading from a file: /sys/class/thermal/thermal_zone0/temp.
This file holds the temperature in milli-degrees Celsius.
$ vcgencmd measure_temp && cat /sys/class/thermal/thermal_zone0/temp temp=47.8'C 47774
So, open the file and read the content. No need to do string processing.
This is, IMHO, the best approach. No libraries, no binary executions. Linux at its best. Thanks for this info!
pip install setuptools sudo pip install git+https://github.com/nicmd/vcgencmd.git
Handy bash script cputemp
(shebang)/usr/bin/python import vcgencmd CPUc=vcgencmd.measure_temp() print str(CPUc) chmod +x cputemp sudo cp cputemp /usr/bin
echo "The CPU is at $(cputemp) degrees C." The CPU is at 39.6 degrees C.
Short and to the point, and in the floating data format for comparisons within the Python program..
«On Stretch there is no vcgencmd command at all.»
vcgencmd commands commands="vcos, ap_output_control, ap_output_post_processing, vchi_test_init, vchi_test_exit, vctest_memmap, vctest_start, vctest_stop, vctest_set, vctest_get, pm_set_policy, pm_get_status, pm_show_stats, pm_start_logging, pm_stop_logging, version, commands, set_vll_dir, set_backlight, set_logging, get_lcd_info, arbiter, cache_flush, otp_dump, test_result, codec_enabled, get_camera, get_mem, measure_clock, measure_volts, scaling_kernel, scaling_sharpness, get_hvs_asserts, get_throttled, measure_temp, get_config, hdmi_ntsc_freqs, hdmi_adjust_clock, hdmi_status_show, hvs_update_fields, pwm_speedup, force_audio, hdmi_stream_channels, hdmi_channel_map, display_power, read_ring_osc, memtest, dispmanx_list, get_rsts, schmoo, render_bar, disk_notify, inuse_notify, sus_suspend, sus_status, sus_is_enabled, sus_stop_test_thread, egl_platform_switch, mem_validate, mem_oom, mem_reloc_stats, hdmi_cvt, hdmi_timings, file" vcgencmd measure_temp temp=42.9'C
Температура CPU, GPU, RAM, с помощью Python
Шаг первый. Скачайте бесплатное программное обеспечение Open Hardware Monitor. Извлеките из архива файл OpenHardwareMonitorLib.dll и поместите его в каталог c будущим проектом.
Шаг второй. Установите пакет pythonnet , который позволит взаимодействовать с DLL.
Шаг третий. Создайте, и запустите представленный ниже Python скрипт от имени администратора.
Вам нужно запустить скрипт от имени администратора, в противном случае код не будет работать должным образом и может не отобразить данные датчиков температуры.
import clr import os hwtypes = ['Mainboard','SuperIO','CPU','RAM','GpuNvidia','GpuAti','TBalancer','Heatmaster','HDD'] def initialize_openhardwaremonitor(): file = rf'\OpenHardwareMonitorLib.dll' clr.AddReference(file) from OpenHardwareMonitor import Hardware handle = Hardware.Computer() handle.MainboardEnabled = True handle.CPUEnabled = True handle.RAMEnabled = True handle.GPUEnabled = True handle.HDDEnabled = True handle.Open() return handle def fetch_stats(handle): for i in handle.Hardware: i.Update() for sensor in i.Sensors: parse_sensor(sensor) for j in i.SubHardware: j.Update() for subsensor in j.Sensors: parse_sensor(subsensor) def parse_sensor(sensor): if sensor.Value: if str(sensor.SensorType) == 'Temperature': result = u'<> <> Temperature Sensor #<> <> - <>\u00B0C'\ .format(hwtypes[sensor.Hardware.HardwareType], sensor.Hardware.Name, sensor.Index, sensor.Name, sensor.Value ) print(result) if __name__ == "__main__": print("OpenHardwareMonitor:") HardwareHandle = initialize_openhardwaremonitor() fetch_stats(HardwareHandle)
Как узнать температуру ЦП в Python 3.8?
Библиотеки pyspectator и psutil не работают. psutil работает лишь на linux, а pyspectator просто отказывается работать. Есть еще какие-нибудь библиотеки?
psutil работает и на windows: github.com/giampaolo/psutil#summary (список из Linux Windows macOS FreeBSD, OpenBSD, NetBSD Sun Solaris AIX). Другое дело, что сенсоры температуры работают только на линуксе: github.com/giampaolo/psutil/issues/1280
1 ответ 1
- модуля pythonnet ( pip install pythonnet ), он позволяет работать с .NET
- библиотеки OpenHardwareMonitorLib.dll
Для получения полной информации нужно запускать скрипт с правами администратора.
import os # pip install pythonnet import clr openhardwaremonitor_hwtypes = [ 'Mainboard', 'SuperIO', 'CPU', 'RAM', 'GpuNvidia', 'GpuAti', 'TBalancer', 'Heatmaster', 'HDD' ] openhardwaremonitor_sensortypes = [ 'Voltage', 'Clock', 'Temperature', 'Load', 'Fan', 'Flow', 'Control', 'Level', 'Factor', 'Power', 'Data', 'SmallData' ] def initialize_openhardwaremonitor(): DIR = os.path.abspath(os.path.dirname(__file__)) dll_file_name = DIR + R'\OpenHardwareMonitorLib.dll' clr.AddReference(dll_file_name) from OpenHardwareMonitor import Hardware handle = Hardware.Computer() handle.MainboardEnabled = True handle.CPUEnabled = True handle.RAMEnabled = True handle.GPUEnabled = True handle.HDDEnabled = True handle.Open() return handle def fetch_stats(handle): for i in handle.Hardware: i.Update() for sensor in i.Sensors: parse_sensor(sensor) for j in i.SubHardware: j.Update() for subsensor in j.Sensors: parse_sensor(subsensor) def parse_sensor(sensor): if sensor.Value is None: return # If SensorType is Temperature if sensor.SensorType == openhardwaremonitor_sensortypes.index('Temperature'): type_name = openhardwaremonitor_hwtypes[sensor.Hardware.HardwareType] print(f" . " f"Temperature Sensor # - °C") if __name__ == "__main__": print("OpenHardwareMonitor:") HardwareHandle = initialize_openhardwaremonitor() fetch_stats(HardwareHandle)
Для дополнительной информации по работе с API OpenHardwareMonitorLib.dll обращайтесь к https://github.com/openhardwaremonitor/openhardwaremonitor/
Пока разбирался, нашел некоторые «подводные камни»:
- Код вида clr.AddReference(‘OpenHardwareMonitorLib.dll’) не работает: нужно или убирать .dll из строки, или указывать абсолютный путь к dll
- Не получится импортировать CPUThermometerLib.dll, т.к. пространство имен CPUThermometer из библиотеки не существует, даже больше — у библиотек OpenHardwareMonitorLib.dll и CPUThermometerLib.dll с какой-то версии пространства одинаковые, что намекает на объединение кода или форк (пруф см. в скриншоте ниже). Поэтому из того ответа убрал использование CPUThermometerLib.dll, оставив OpenHardwareMonitorLib.dll
- Библиотеку OpenHardwareMonitorLib.dll можно будет скачать с офф. сайта (скачать и вытащить из архива с программой) или сразу из папки примера
CPUThermometerLib.dll и OpenHardwareMonitorLib.dll одно и тоже:
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
A python applet that monitors my CPU temperature and blares a warning siren when it gets too hot
Ayilay/CPUTempMonitor
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
My Lenovo T430 laptop heats up alot to the point where it shuts down without warning. Alot means 105 °C. It doesn’t always heat up that much, but when it does, it does so without warning, and I have lost data because of it.
It heats up because it is connected to 3 monitors via a docking station which obstructs much of the cooling ports. Silly design if you ask me, but alas laptops also were not designed to be used as desktops the way I am using it.
EDIT: I recently drilled ALOT of holes into my docking station, to allow for better airflow of hot air out of the laptop. There’s still some obstruction of air due to the dock mechanism that ejects my laptop. It seemed to help slightly, because I can stay on Zoom calls for longer, BUT eventually it still reached the 95C temperature that triggers the sirens.
This applet reads my CPU temperatures every 2 seconds, and displays them. If the largest of the two temperatures exceeds a «High» temperature threshold, it blares a siren and generates a desktop notification.
The siren stops when the highest of the two core temperatures drops below a «Low» temperature threshold.
This was a silly project I made to familiarize myself with PyQt so don’t expect this to work if you don’t have a non-linux laptop that isn’t a Lenovo T430. But be my guest and try it, and tell me if it works 🙂
To use this, make sure you have python3 installed, as well as pip (use your package manager to obtain these if you don’t have them).
Clone this repository, cd into it, and run the following commands (without the ‘$’):
$ python -m venv _venv # This is only required ONCE $ . _venv/bin/activate $ pip install -r requirements.txt
This will create a python virtual environment, and install all necessary packages using the requirements.txt file.
If you close your terminal window and want to resume work on this project, reactivate the virtual environment as follows:
Why this applet is useful
My computer doesn’t always heat up obnoxiously to the point where it shuts down. It usually does so if I’m gaming, or if I’m doing heavy media rendering like using CAD software or watching cat videos during boring zoom meetings online classes.
When the siren activates, I use my can of compressed air to rapidly cool down my computer to a nominal level. Is it the smartest solution? Probably not. But using a laptop cooler and keeping the laptop lid open all the time actually isn’t as helpful as one would expect, and I need my laptop to work as a desktop because I also need it to work as a laptop when I go to school. So this is currently the best solution ¯\_(ツ)_/¯
True, 105 is very hot. I haven’t directly measured my CPU reaching such temperatures. My guestimation of 105 degrees comes from these two facts:
- 105 degrees is what the sensors command lists as my CPU’s «critical» temperature. Thus I assume that is the point where it automatically shuts down with no warning
- When I’m gaming, I easily record temperatures of 95 degrees. It’s wild.
Why don’t you keep the laptop lid open?
Maybe your fan has lint and s**t stuck in there that you can clean out.
My fan is clean. I opened my laptop up and blew compressed air at it. I wish this was the problem.
You could make a liquid cooling system?
That’s alot of effort and I’m not feeling it. Also I might get a new laptop soon that heats less or has a better docking station that allows for better ventilation.
I know. I was bored when I wrote it. I should be doing physics homework right now.
About
A python applet that monitors my CPU temperature and blares a warning siren when it gets too hot