Температура процессора python psutil
Запись: xintrea/mytetra_db_adgaver_new/master/base/1544726836o5ex6f60ts/text.html на raw.githubusercontent.com
Как узнать температуру процессора с помощью psutil в Python
Библиотека psutil предназначена для получения информации о запущенных процессах и использовании системы (процессор, память, диски, сеть).
Эта библиотека пригодится вам, если вы захотите получить какие-либо данные о конкретном процессе или комплектующих. Также появится возможность управлять ими в зависимости от их состояния.
Получение информации о комплектующих ПК с помощью библиотеки psutil
Какую же информацию можно получить? Можно достать данные о процессоре с момента загрузки, в том числе о том, сколько системных вызовов и контекстных переключателей он сделал:
I n [ 1 ] : psutil . cpu_stats ()
Также есть возможность извлечь информацию о диске и состоянии памяти:
I n [ 1 ] : psutil . disk_usage ( «c:» ) Out [ 1 ] : sdiskusage ( total = 127950385152L ,
I n [ 2 ] : psutil . virtual_memory ()
O ut [ 2 ] : svmem ( total = 8488030208L ,
Можно даже получить данные о времени автономной работы или узнать текущую температуру процессора:
I n [ 1 ] : psutil . sensors_battery ()
O ut [ 1 ] : sbattery ( percent = 77 , secsleft = 18305 , power_plugged = False )
I n [ 2 ] : psutil . sensors_temperatures () # In Celsius
Получение информации о процессах
О дной из самых классных фишек этой библиотеки является то, что можно получить доступ к процессам и их статистике. Однако есть процессы, которые требуют наличия прав администратора. В противном случае после попытки доступа произойдет сбой с ошибкой «AccessDenied». Давайте протестируем эту функцию.
Сначала создадим экземпляр, предоставляя требуемый идентификатор процесса:
I n [ 1 ] : p = psutil . Process ( 9800 )
Затем можно получить доступ ко всей информации и статистике процесса:
O ut [ 1 ] : ‘C:\\Windows\\System32\\dllhost.exe’
O ut [ 3 ] : ‘C:\\WINDOWS\\system32’
Создадим функцию, которая связывает открытые порты соединений с процессами. Для начала нужно перебрать все открытые соединения.
I n [ 1 ] : ps . net_connections ?
S ignature : ps . net_connections ( kind = ‘inet’ )
R eturn system — wide socket connections as a list of
( fd , family , type , laddr , raddr , status , pid ) namedtuples .
I n case of limited privileges ‘fd’ and ‘pid’ may be set to — 1
T he * kind * parameter filters for connections that fit the
| Kind Value | Connections using |
| unix | UNIX socket ( both UDP and TCP protocols ) |
| all | the sum of all the possible families and protocols |
Обратим внимание на то, что одним из возвращаемых атрибутов является «pid».
Можно связать это с именем процесса:
I n [ 1 ] : def link_connection_to_process () :
. : for connection in ps . net_connections () :
. : yield [ ps . Process ( pid = connection . pid ). name (),
. : continue # Keep going if we don’t have access
Но не стоит забывать, что если пользователь не обладает правами администратора, он не сможет получить доступ к определенным процессам. Проверим выходные данные. Он вернет много данных, поэтому выведем только первое значение:
I n [ 1 ] : for proc_to_con in ps . net_connections () :
[ ‘ManagementServer.exe’ , sconn ( fd =- 1 , family = 2 , type = 1 ,laddr = addr ( ip = ‘127.0.0.1’ , port = 5905 ), raddr = addr ( ip = ‘127.0.0.1’ , port = 49728 ),
status = ‘ESTABLISHED’ , pid = 5224 )]
Как можно увидеть, первое значение – это имя процесса, второй – данные соединения: IP-адрес, порт, статус и так далее. Данная функция очень полезна для понимания того, какие порты используются конкретными процессами.
Psutil – отличная библиотека, предназначенная для управления системой. Она полезна для управления ресурсами как частью потока кода.
- Как изменить системную переменную path в Windows 7
- Приступая к работе
- PLEAC-Python
- Язык программирования Python 3 для начинающих и чайников
- Программирование на Python: от новичка до профессионала
- Странности языка Python, которые могут вас укусить
- ‘================= Питон на русском
- ‘================= В глубь языка Python
- OverAPI.com
- Python Tutorial
- PyCharm IDE для Python программистов
- Python2 vs Python3: различия синтаксиса
- Документирование кода в Python. PEP 257
- PEP 8 — руководство по написанию кода на Python
- Работа с модулями: создание, подключение инструкциями import и from
- With . as — менеджеры контекста
- Перегрузка операторов
- Инкапсуляция, наследование, полиморфизм
- Первая программа. Среда разработки IDLE
- Форматирование строк. Оператор %
- Возможности языка python
- Ключевые слова, модуль keyword
- Встроенные функции
- Циклы for и while, операторы break и continue, волшебное слово else
- Инструкция if-elif-else, проверка истинности, трехместное выражение if/else
- Синтаксис языка Python
- Компиляция программы на python 3 в exe с помощью программы cx_Freeze
- Как определять функции в Python 3
- Функции Print() в Python
- Как массивы и списки работают на Python
- Руководство по словарям Python
- Применение Python в качестве калькулятора
- Используйте Psyco, и Python будет работать так же быстро, как и С
- Определение страны по IP-адресу
- Функциональное программирование на языке Python
- Интерполяция строк
- Python — основные концепции
- Текстовая обработка в языке Python. Подсказки для начинающих.
- Устанавливаем python-пакеты с помощью pip
- Управление Python пакетами с помощью pip
- PyQt или PySide — какой из них использовать
- Как узнать температуру процессора с помощью psutil в Python
- Python GUI: создаём простое приложение с PyQt и Qt Designer
- Сайт с нуля на python и django. Работа с постами на сайте. Делаем аналог livejournal.
- Все о языке программирования Python: новости развития
Check the temperature of your CPU using Python (and other cool tricks)
Python’s psutil module provides an interface with all the PC resources and processes.
This module is very helpful whether we want to get some data on a specific resource or manage a resource according to its state.
In this article, I will show you the main features of this module and how to use them.
Getting PC resources information
Let’s see how we can get some info about our PC’s current system state.
We can get some info about the CPU since boot time, including how many system calls and context switches it has made:
In [1]: psutil.cpu_stats()Out[1]: scpustats(ctx_switches=437905181,interrupts=2222556355L,soft_interrupts=0,syscalls=109468308)
We can get some info about the disk and the memory state:
In [1]: psutil.disk_usage("c:")Out[1]: sdiskusage(total=127950385152L, used=116934914048L, free=11015471104L, percent=91.4)
In [2]: psutil.virtual_memory()Out[2]: svmem(total=8488030208L, available=3647520768L, percent=57.0, used=4840509440L, free=3647520768L)
We can even get some physical information about how many seconds of battery life is left, or the current CPU temperature:
In [1]: psutil.sensors_battery()Out[1]: sbattery(percent=77, secsleft=18305, power_plugged=False)
In [2]: psutil.sensors_temperatures() # In CelsiusOut[2]:
Getting Information about Processes
One of the most powerful features this module provides us is the “Process” class. We can access each process’ resources and statistics and respond accordingly.
(There are processes that require some admin or system privileges, so after trying to access their instance it will fail with an “AccessDenied” error.)
Let’s check this feature out.
First, we create an instance by giving the wanted process ID:
In [1]: p = psutil.Process(9800)
Then, we can access all the information and statistics of the process:
In [1]: p.exe()Out[1]: 'C:\\Windows\\System32\\dllhost.exe'
In [3]: p.cwd()Out[3]: 'C:\\WINDOWS\\system32'
Let’s create a function that links open connections ports to processes.
First, we need to iterate all the open connections. ps.net_connections is exactly what we need!
In [1]: ps.net_connections?Signature: ps.net_connections(kind='inet')Docstring:Return system-wide socket connections as a list of(fd, family, type, laddr, raddr, status, pid) namedtuples.In case of limited privileges 'fd' and 'pid' may be set to -1and None respectively.The *kind* parameter filters for connections that fit thefollowing criteria:
+------------+----------------------------------------------------+| Kind Value | Connections using |+------------+----------------------------------------------------+| inet | IPv4 and IPv6 || inet4 | IPv4 || inet6 | IPv6 || tcp | TCP || tcp4 | TCP over IPv4 || tcp6 | TCP over IPv6 || udp | UDP || udp4 | UDP over IPv4 || udp6 | UDP over IPv6 || unix | UNIX socket (both UDP and TCP protocols) || all | the sum of all the possible families and protocols |+------------+----------------------------------------------------+
We can see that one of the attributes that net_connections returns is “pid”.
We can link this to a process name:
In [1]: def link_connection_to_process(): . for connection in ps.net_connections(): . try: . yield [ps.Process(pid=connection.pid).name(), . connection] . except ps.AccessDenied: . continue # Keep going if we don't have access
We should remember that unless we’ve got some root privileges, we cannot access particular processes. Therefore we need to wrap it in a try-catch statement for handling an “AccessDenied” error.
It will output a lot of data, so let’s print the first member:
In [1]: for proc_to_con in ps.net_connections(): . print proc_to_con . raw_input(". ") . ['ManagementServer.exe', sconn(fd=-1, family=2, type=1, laddr=addr(ip='127.0.0.1', port=5905), raddr=addr(ip='127.0.0.1', port=49728), status='ESTABLISHED', pid=5224)].
As we can see, the first member is the process name and the second is the connection data: ip address, port, status and so on.
This function is very useful to explore which ports are used by each processes.
We’ve all gotten the error “This address is already in use” once, haven’t we?
Conclusion
The psutil module is a great library for system management. It is useful for managing resources as a part of a code flow.
I hope this article taught you something new, and I am looking forward to your feedback. Please, do tell — was this useful for you?