Как узнать температуру процессора в windows 10 python

I need an example code for accessing CPU temperature in python. I'm running windows 7, BTW.

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

I was wondering if there was a way to get the CPU and the GPU temperature in python. I have already found a way for Linux (using psutil.sensors_temperature()), and I wanted to find a way for Windows.

A way to find the temperatures for Mac OS would also be appreciated, but I mainly want a way for windows.

I prefer to only use python modules, but DLL and C/C++ extensions are also completely acceptable!

When I try doing the below, I get None:

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

When I try doing the below, I get an error:

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

Error:

wmi.x_wmi: <x_wmi: Unexpected COM Error (-2147217396, 'OLE error 0x8004100c', None, None)>

I have heard of OpenHardwareMoniter, but this requires me to install something that is not a python module. I would also prefer to not have to run the script as admin to get the results.

I am also fine with running windows cmd commands with python, but I have not found one that returns the CPU temp.

Update: I found this: https://stackoverflow.com/a/58924992/13710015.
I can’t figure out how to use it though.
When I tried doing: print(OUTPUT_temp._fields_), I got

[('Board Temp', <class 'ctypes.c_ulong'>), ('CPU Temp', <class 'ctypes.c_ulong'>), ('Board Temp2', <class 'ctypes.c_ulong'>), ('temp4', <class 'ctypes.c_ulong'>), ('temp5', <class 'ctypes.c_ulong'>)]

Note: I really do not want to run this as admin. If I absolutely have to, I can, but I prefer not to.

I was wondering if there was a way to get the CPU and the GPU temperature in python. I have already found a way for Linux (using psutil.sensors_temperature()), and I wanted to find a way for Windows.

A way to find the temperatures for Mac OS would also be appreciated, but I mainly want a way for windows.

I prefer to only use python modules, but DLL and C/C++ extensions are also completely acceptable!

When I try doing the below, I get None:

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

When I try doing the below, I get an error:

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

Error:

wmi.x_wmi: <x_wmi: Unexpected COM Error (-2147217396, 'OLE error 0x8004100c', None, None)>

I have heard of OpenHardwareMoniter, but this requires me to install something that is not a python module. I would also prefer to not have to run the script as admin to get the results.

I am also fine with running windows cmd commands with python, but I have not found one that returns the CPU temp.

Update: I found this: https://stackoverflow.com/a/58924992/13710015.
I can’t figure out how to use it though.
When I tried doing: print(OUTPUT_temp._fields_), I got

[('Board Temp', <class 'ctypes.c_ulong'>), ('CPU Temp', <class 'ctypes.c_ulong'>), ('Board Temp2', <class 'ctypes.c_ulong'>), ('temp4', <class 'ctypes.c_ulong'>), ('temp5', <class 'ctypes.c_ulong'>)]

Note: I really do not want to run this as admin. If I absolutely have to, I can, but I prefer not to.


This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters

Show hidden characters

import wmi
def avg(value_list):
num = 0
length = len(value_list)
for val in value_list:
num += val
return num/length
w = wmi.WMI(namespace=«root\OpenHardwareMonitor»)
sensors = w.Sensor()
cpu_temps = []
gpu_temp = 0
for sensor in sensors:
if sensor.SensorType==u’Temperature’ and not ‘GPU’ in sensor.Name:
cpu_temps += [float(sensor.Value)]
elif sensor.SensorType==u’Temperature’ and ‘GPU’ in sensor.Name:
gpu_temp = sensor.Value
print «Avg CPU: {}».format(avg(cpu_temps))
print «GPU: {}».format(gpu_temp)

Содержание

  1. Check the temperature of your CPU using Python (and other cool tricks)
  2. Getting PC resources information
  3. Getting Information about Processes
  4. Conclusion
  5. chand1012 / temps.py
  6. Как узнать температуру процессора с помощью psutil в Python
  7. Получение информации о комплектующих ПК с помощью библиотеки psutil
  8. Получение информации о процессах
  9. Подведение итогов
  10. psutil documentation¶
  11. Quick links¶
  12. About¶
  13. Funding¶
  14. Sponsors¶
  15. Supporters¶
  16. Install¶
  17. System related functions¶
  18. Memory¶
  19. Disks¶
  20. Network¶
  21. Sensors¶
  22. Other system info¶
  23. Processes¶
  24. Functions¶
  25. Exceptions¶
  26. Process class¶
  27. Windows services¶

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:

We can get some info about the disk and the memory state:

We can even get some physical information about how many seconds of battery life is left, or the current CPU temperature:

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:

Then, we can access all the information and statistics of the process:

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!

We can see that one of the attributes that net_connections returns is “pid”.

We can link this to a process name:

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.

Let’s check the output.

It will output a lot of data, so let’s print the first member:

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?

Источник

chand1012 / temps.py

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

import wmi
def avg ( value_list ):
num = 0
length = len ( value_list )
for val in value_list :
num += val
return num / length
w = wmi . WMI ( namespace = «root \ OpenHardwareMonitor» )
sensors = w . Sensor ()
cpu_temps = []
gpu_temp = 0
for sensor in sensors :
if sensor . SensorType == u’Temperature’ and not ‘GPU’ in sensor . Name :
cpu_temps += [ float ( sensor . Value )]
elif sensor . SensorType == u’Temperature’ and ‘GPU’ in sensor . Name :
gpu_temp = sensor . Value
print «Avg CPU: <>» . format ( avg ( cpu_temps ))
print «GPU: <>» . format ( gpu_temp )

how I can show only the temperature of my cpu for example?

memory usage rises all the time.

i got to have this error

$ python -u «d:kshitijpythonoverlaycpu_temp.py»
Traceback (most recent call last):
File «D:programspythonpython3.10libsite-packageswmi.py», line 1340, in connect
obj = GetObject(moniker)
File «D:programspythonpython3.10libsite-packageswin32comclient_init_.py», line 85, in GetObject
return Moniker(Pathname, clsctx)
File «D:programspythonpython3.10libsite-packageswin32comclient_init_.py», line 102, in Moniker
moniker, i, bindCtx = pythoncom.MkParseDisplayName(Pathname)
pywintypes.com_error: (-2147217394, ‘OLE error 0x8004100e’, None, None)

During handling of the above exception, another exception occurred:

Источник

Как узнать температуру процессора с помощью psutil в Python

Библиотека psutil предназначена для получения информации о запущенных процессах и использовании системы (процессор, память, диски, сеть).


Эта библиотека пригодится вам, если вы захотите получить какие-либо данные о конкретном процессе или комплектующих. Также появится возможность управлять ими в зависимости от их состояния.

Получение информации о комплектующих ПК с помощью библиотеки psutil

Какую же информацию можно получить? Можно достать данные о процессоре с момента загрузки, в том числе о том, сколько системных вызовов и контекстных переключателей он сделал:

Также есть возможность извлечь информацию о диске и состоянии памяти:

Можно даже получить данные о времени автономной работы или узнать текущую температуру процессора:

Получение информации о процессах

Одной из самых классных фишек этой библиотеки является то, что можно получить доступ к процессам и их статистике. Однако есть процессы, которые требуют наличия прав администратора. В противном случае после попытки доступа произойдет сбой с ошибкой «AccessDenied». Давайте протестируем эту функцию.

Сначала создадим экземпляр, предоставляя требуемый идентификатор процесса:

Затем можно получить доступ ко всей информации и статистике процесса:

Создадим функцию, которая связывает открытые порты соединений с процессами. Для начала нужно перебрать все открытые соединения.

Обратим внимание на то, что одним из возвращаемых атрибутов является «pid».

Можно связать это с именем процесса:

Но не стоит забывать, что если пользователь не обладает правами администратора, он не сможет получить доступ к определенным процессам. Проверим выходные данные. Он вернет много данных, поэтому выведем только первое значение:

Как можно увидеть, первое значение – это имя процесса, второй – данные соединения: IP-адрес, порт, статус и так далее. Данная функция очень полезна для понимания того, какие порты используются конкретными процессами.

Подведение итогов

Psutil – отличная библиотека, предназначенная для управления системой. Она полезна для управления ресурсами как частью потока кода.

Источник

psutil documentation¶

Quick links¶

About¶

psutil (python system and process utilities) is a cross-platform library for retrieving information on running processes and system utilization (CPU, memory, disks, network, sensors) in Python. It is useful mainly for system monitoring, profiling, limiting process resources and the management of running processes. It implements many functionalities offered by UNIX command line tools such as: ps, top, lsof, netstat, ifconfig, who, df, kill, free, nice, ionice, iostat, iotop, uptime, pidof, tty, taskset, pmap. psutil currently supports the following platforms:

  • Linux
  • Windows
  • macOS
  • FreeBSD, OpenBSD, NetBSD
  • Sun Solaris
  • AIX

Supported Python versions are 2.7 and 3.4+. PyPy is also known to work.

The psutil documentation you’re reading is distributed as a single HTML page.

Funding¶

While psutil is free software and will always be, the project would benefit immensely from some funding. Keeping up with bug reports and maintenance has become hardly sustainable for me alone in terms of time. If you’re a company that’s making significant use of psutil you can consider becoming a sponsor via GitHub, Open Collective or PayPal and have your logo displayed in here and psutil doc.

Supporters¶

Install¶

On Linux, Windows, macOS:

For other platforms see more detailed install instructions.

Return system CPU times as a named tuple. Every attribute represents the seconds the CPU has spent in the given mode. The attributes availability varies depending on the platform:

  • user: time spent by normal processes executing in user mode; on Linux this also includes guest time
  • system: time spent by processes executing in kernel mode
  • idle: time spent doing nothing
  • nice(UNIX): time spent by niced (prioritized) processes executing in user mode; on Linux this also includes guest_nice time
  • iowait(Linux): time spent waiting for I/O to complete. This is not accounted in idle time counter.
  • irq(Linux, BSD): time spent for servicing hardware interrupts
  • softirq(Linux): time spent for servicing software interrupts
  • steal(Linux 2.6.11+): time spent by other operating systems running in a virtualized environment
  • guest(Linux 2.6.24+): time spent running a virtual CPU for guest operating systems under the control of the Linux kernel
  • guest_nice(Linux 3.2.0+): time spent running a niced guest (virtual CPU for guest operating systems under the control of the Linux kernel)
  • interrupt(Windows): time spent for servicing hardware interrupts ( similar to “irq” on UNIX)
  • dpc(Windows): time spent servicing deferred procedure calls (DPCs); DPCs are interrupts that run at a lower priority than standard interrupts.

When percpu is True return a list of named tuples for each logical CPU on the system. First element of the list refers to first CPU, second element to second CPU and so on. The order of the list is consistent across calls. Example output on Linux:

Changed in version 4.1.0: added interrupt and dpc fields on Windows.

CPU times are always supposed to increase over time, or at least remain the same, and that’s because time cannot go backwards. Surprisingly sometimes this might not be the case (at least on Windows and Linux), see #1210.

Return a float representing the current system-wide CPU utilization as a percentage. When interval is > 0.0 compares system CPU times elapsed before and after the interval (blocking). When interval is 0.0 or None compares system CPU times elapsed since last call or module import, returning immediately. That means the first time this is called it will return a meaningless 0.0 value which you are supposed to ignore. In this case it is recommended for accuracy that this function be called with at least 0.1 seconds between calls. When percpu is True returns a list of floats representing the utilization as a percentage for each CPU. First element of the list refers to first CPU, second element to second CPU and so on. The order of the list is consistent across calls.

the first time this function is called with interval = 0.0 or None it will return a meaningless 0.0 value which you are supposed to ignore.

Same as cpu_percent() but provides utilization percentages for each specific CPU time as is returned by psutil.cpu_times(percpu=True) . interval and percpu arguments have the same meaning as in cpu_percent() . On Linux “guest” and “guest_nice” percentages are not accounted in “user” and “user_nice” percentages.

the first time this function is called with interval = 0.0 or None it will return a meaningless 0.0 value which you are supposed to ignore.

Changed in version 4.1.0: two new interrupt and dpc fields are returned on Windows.

Return the number of logical CPUs in the system (same as os.cpu_count in Python 3.4) or None if undetermined. “logical CPUs” means the number of physical cores multiplied by the number of threads that can run on each core (this is known as Hyper Threading). If logical is False return the number of physical cores only, or None if undetermined. On OpenBSD and NetBSD psutil.cpu_count(logical=False) always return None . Example on a system having 2 cores + Hyper Threading:

Note that psutil.cpu_count() may not necessarily be equivalent to the actual number of CPUs the current process can use. That can vary in case process CPU affinity has been changed, Linux cgroups are being used or (in case of Windows) on systems using processor groups or having more than 64 CPUs. The number of usable CPUs can be obtained with:

Return various CPU statistics as a named tuple:

  • ctx_switches: number of context switches (voluntary + involuntary) since boot.
  • interrupts: number of interrupts since boot.
  • soft_interrupts: number of software interrupts since boot. Always set to 0 on Windows and SunOS.
  • syscalls: number of system calls since boot. Always set to 0 on Linux.

New in version 4.1.0.

Return CPU frequency as a named tuple including current, min and max frequencies expressed in Mhz. On Linux current frequency reports the real-time value, on all other platforms this usually represents the nominal “fixed” value (never changing). If percpu is True and the system supports per-cpu frequency retrieval (Linux only) a list of frequencies is returned for each CPU, if not, a list with a single element is returned. If min and max cannot be determined they are set to 0.0 .

Availability: Linux, macOS, Windows, FreeBSD, OpenBSD

New in version 5.1.0.

Changed in version 5.5.1: added FreeBSD support.

Changed in version 5.9.1: added OpenBSD support.

Return the average system load over the last 1, 5 and 15 minutes as a tuple. The “load” represents the processes which are in a runnable state, either using the CPU or waiting to use the CPU (e.g. waiting for disk I/O). On UNIX systems this relies on os.getloadavg. On Windows this is emulated by using a Windows API that spawns a thread which keeps running in background and updates results every 5 seconds, mimicking the UNIX behavior. Thus, on Windows, the first time this is called and for the next 5 seconds it will return a meaningless (0.0, 0.0, 0.0) tuple. The numbers returned only make sense if related to the number of CPU cores installed on the system. So, for instance, a value of 3.14 on a system with 10 logical CPUs means that the system load was 31.4% percent over the last N minutes.

Availability: Unix, Windows

New in version 5.6.2.

Memory¶

Return statistics about system memory usage as a named tuple including the following fields, expressed in bytes. Main metrics:

  • total: total physical memory (exclusive swap).
  • available: the memory that can be given instantly to processes without the system going into swap. This is calculated by summing different memory values depending on the platform and it is supposed to be used to monitor actual memory usage in a cross platform fashion.
  • used: memory used, calculated differently depending on the platform and designed for informational purposes only. total — free does not necessarily match used.
  • free: memory not being used at all (zeroed) that is readily available; note that this doesn’t reflect the actual memory available (use available instead). total — used does not necessarily match free.
  • active(UNIX): memory currently in use or very recently used, and so it is in RAM.
  • inactive(UNIX): memory that is marked as not used.
  • buffers(Linux, BSD): cache for things like file system metadata.
  • cached(Linux, BSD): cache for various things.
  • shared(Linux, BSD): memory that may be simultaneously accessed by multiple processes.
  • slab(Linux): in-kernel data structures cache.
  • wired(BSD, macOS): memory that is marked to always stay in RAM. It is never moved to disk.

The sum of used and available does not necessarily equal total. On Windows available and free are the same. See meminfo.py script providing an example on how to convert bytes in a human readable form.

if you just want to know how much physical memory is left in a cross platform fashion simply rely on the available field.

Changed in version 4.2.0: added shared metric on Linux.

Changed in version 5.4.4: added slab metric on Linux.

Return system swap memory statistics as a named tuple including the following fields:

  • total: total swap memory in bytes
  • used: used swap memory in bytes
  • free: free swap memory in bytes
  • percent: the percentage usage calculated as (total — available) / total * 100
  • sin: the number of bytes the system has swapped in from disk (cumulative)
  • sout: the number of bytes the system has swapped out from disk (cumulative)

sin and sout on Windows are always set to 0 . See meminfo.py script providing an example on how to convert bytes in a human readable form.

Changed in version 5.2.3: on Linux this function relies on /proc fs instead of sysinfo() syscall so that it can be used in conjunction with psutil.PROCFS_PATH in order to retrieve memory info about Linux containers such as Docker and Heroku.

Disks¶

Return all mounted disk partitions as a list of named tuples including device, mount point and filesystem type, similarly to “df” command on UNIX. If all parameter is False it tries to distinguish and return physical devices only (e.g. hard disks, cd-rom drives, USB keys) and ignore all others (e.g. pseudo, memory, duplicate, inaccessible filesystems). Note that this may not be fully reliable on all systems (e.g. on BSD this parameter is ignored). See disk_usage.py script providing an example usage. Returns a list of named tuples with the following fields:

  • device: the device path (e.g. «/dev/hda1» ). On Windows this is the drive letter (e.g. «C:\» ).
  • mountpoint: the mount point path (e.g. «/» ). On Windows this is the drive letter (e.g. «C:\» ).
  • fstype: the partition filesystem (e.g. «ext3» on UNIX or «NTFS» on Windows).
  • opts: a comma-separated string indicating different mount options for the drive/partition. Platform-dependent.
  • maxfile: the maximum length a file name can have.
  • maxpath: the maximum length a path name (directory name + base file name) can have.

Changed in version 5.7.4: added maxfile and maxpath fields

Return disk usage statistics about the partition which contains the given path as a named tuple including total, used and free space expressed in bytes, plus the percentage usage. OSError is raised if path does not exist. Starting from Python 3.3 this is also available as shutil.disk_usage (see BPO-12442). See disk_usage.py script providing an example usage.

UNIX usually reserves 5% of the total disk space for the root user. total and used fields on UNIX refer to the overall total and used space, whereas free represents the space available for the user and percent represents the user utilization (see source code). That is why percent value may look 5% bigger than what you would expect it to be. Also note that both 4 values match “df” cmdline utility.

Changed in version 4.3.0: percent value takes root reserved space into account.

Return system-wide disk I/O statistics as a named tuple including the following fields:

  • read_count: number of reads
  • write_count: number of writes
  • read_bytes: number of bytes read
  • write_bytes: number of bytes written
  • read_time: (all except NetBSD and OpenBSD) time spent reading from disk (in milliseconds)
  • write_time: (all except NetBSD and OpenBSD) time spent writing to disk (in milliseconds)
  • busy_time: (Linux, FreeBSD) time spent doing actual I/Os (in milliseconds)
  • read_merged_count (Linux): number of merged reads (see iostats doc)
  • write_merged_count (Linux): number of merged writes (see iostats doc)

If perdisk is True return the same information for every physical disk installed on the system as a dictionary with partition names as the keys and the named tuple described above as the values. See iotop.py for an example application. On some systems such as Linux, on a very busy or long-lived system, the numbers returned by the kernel may overflow and wrap (restart from zero). If nowrap is True psutil will detect and adjust those numbers across function calls and add “old value” to “new value” so that the returned numbers will always be increasing or remain the same, but never decrease. disk_io_counters.cache_clear() can be used to invalidate the nowrap cache. On Windows it may be ncessary to issue diskperf -y command from cmd.exe first in order to enable IO counters. On diskless machines this function will return None or <> if perdisk is True .

on Windows «diskperf -y» command may need to be executed first otherwise this function won’t find any disk.

Changed in version 5.3.0: numbers no longer wrap (restart from zero) across calls thanks to new nowrap argument.

Changed in version 4.0.0: added busy_time (Linux, FreeBSD), read_merged_count and write_merged_count (Linux) fields.

Changed in version 4.0.0: NetBSD no longer has read_time and write_time fields.

Network¶

Return system-wide network I/O statistics as a named tuple including the following attributes:

  • bytes_sent: number of bytes sent
  • bytes_recv: number of bytes received
  • packets_sent: number of packets sent
  • packets_recv: number of packets received
  • errin: total number of errors while receiving
  • errout: total number of errors while sending
  • dropin: total number of incoming packets which were dropped
  • dropout: total number of outgoing packets which were dropped (always 0 on macOS and BSD)

If pernic is True return the same information for every network interface installed on the system as a dictionary with network interface names as the keys and the named tuple described above as the values. On some systems such as Linux, on a very busy or long-lived system, the numbers returned by the kernel may overflow and wrap (restart from zero). If nowrap is True psutil will detect and adjust those numbers across function calls and add “old value” to “new value” so that the returned numbers will always be increasing or remain the same, but never decrease. net_io_counters.cache_clear() can be used to invalidate the nowrap cache. On machines with no network interfaces this function will return None or <> if pernic is True .

Also see nettop.py and ifconfig.py for an example application.

Changed in version 5.3.0: numbers no longer wrap (restart from zero) across calls thanks to new nowrap argument.

Return system-wide socket connections as a list of named tuples. Every named tuple provides 7 attributes:

  • fd: the socket file descriptor. If the connection refers to the current process this may be passed to socket.fromfd to obtain a usable socket object. On Windows and SunOS this is always set to -1 .
  • family: the address family, either AF_INET, AF_INET6 or AF_UNIX.
  • type: the address type, either SOCK_STREAM, SOCK_DGRAM or SOCK_SEQPACKET.
  • laddr: the local address as a (ip, port) named tuple or a path in case of AF_UNIX sockets. For UNIX sockets see notes below.
  • raddr: the remote address as a (ip, port) named tuple or an absolute path in case of UNIX sockets. When the remote endpoint is not connected you’ll get an empty tuple (AF_INET*) or «» (AF_UNIX). For UNIX sockets see notes below.
  • status: represents the status of a TCP connection. The return value is one of the psutil.CONN_* constants (a string). For UDP and UNIX sockets this is always going to be psutil.CONN_NONE .
  • pid: the PID of the process which opened the socket, if retrievable, else None . On some platforms (e.g. Linux) the availability of this field changes depending on process privileges (root is needed).

The kind parameter is a string which filters for connections matching the following 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

On macOS and AIX this function requires root privileges. To get per-process connections use Process.connections() . Also, see netstat.py example script. Example:

(macOS and AIX) psutil.AccessDenied is always raised unless running as root. This is a limitation of the OS and lsof does the same.

(Solaris) UNIX sockets are not supported.

(Linux, FreeBSD) “raddr” field for UNIX sockets is always set to “”. This is a limitation of the OS.

(OpenBSD) “laddr” and “raddr” fields for UNIX sockets are always set to “”. This is a limitation of the OS.

New in version 2.1.0.

Changed in version 5.3.0: : socket “fd” is now set for real instead of being -1 .

Changed in version 5.3.0: : “laddr” and “raddr” are named tuples.

Return the addresses associated to each NIC (network interface card) installed on the system as a dictionary whose keys are the NIC names and value is a list of named tuples for each address assigned to the NIC. Each named tuple includes 5 fields:

  • family: the address family, either AF_INET or AF_INET6 or psutil.AF_LINK , which refers to a MAC address.
  • address: the primary NIC address (always set).
  • netmask: the netmask address (may be None ).
  • broadcast: the broadcast address (may be None ).
  • ptp: stands for “point to point”; it’s the destination address on a point to point interface (typically a VPN). broadcast and ptp are mutually exclusive. May be None .

See also nettop.py and ifconfig.py for an example application.

if you’re interested in others families (e.g. AF_BLUETOOTH) you can use the more powerful netifaces extension.

you can have more than one address of the same family associated with each interface (that’s why dict values are lists).

broadcast and ptp are not supported on Windows and are always None .

New in version 3.0.0.

Changed in version 3.2.0: ptp field was added.

Changed in version 4.4.0: added support for netmask field on Windows which is no longer None .

Return information about each NIC (network interface card) installed on the system as a dictionary whose keys are the NIC names and value is a named tuple with the following fields:

isup: a bool indicating whether the NIC is up and running (meaning ethernet cable or Wi-Fi is connected).

duplex: the duplex communication type; it can be either NIC_DUPLEX_FULL , NIC_DUPLEX_HALF or NIC_DUPLEX_UNKNOWN .

speed: the NIC speed expressed in mega bits (MB), if it can’t be determined (e.g. ‘localhost’) it will be set to 0 .

mtu: NIC’s maximum transmission unit expressed in bytes.

flags: a string of comma-separated flags on the interface (may be an empty string). Possible flags are: up , broadcast , debug , loopback , pointopoint , notrailers , running , noarp , promisc , allmulti , master , slave , multicast , portsel , dynamic , oactive , simplex , link0 , link1 , link2 , and d2 (some flags are only available on certain platforms).

Also see nettop.py and ifconfig.py for an example application.

New in version 3.0.0.

Changed in version 5.7.3: isup on UNIX also checks whether the NIC is running.

Changed in version 5.9.3: flags field was added on POSIX.

Sensors¶

Return hardware temperatures. Each entry is a named tuple representing a certain hardware temperature sensor (it may be a CPU, an hard disk or something else, depending on the OS and its configuration). All temperatures are expressed in celsius unless fahrenheit is set to True . If sensors are not supported by the OS an empty dict is returned. Example:

See also temperatures.py and sensors.py for an example application.

Availability: Linux, FreeBSD

New in version 5.1.0.

Changed in version 5.5.0: added FreeBSD support

Return hardware fans speed. Each entry is a named tuple representing a certain hardware sensor fan. Fan speed is expressed in RPM (revolutions per minute). If sensors are not supported by the OS an empty dict is returned. Example:

See also fans.py and sensors.py for an example application.

New in version 5.2.0.

Return battery status information as a named tuple including the following values. If no battery is installed or metrics can’t be determined None is returned.

  • percent: battery power left as a percentage.
  • secsleft: a rough approximation of how many seconds are left before the battery runs out of power. If the AC power cable is connected this is set to psutil.POWER_TIME_UNLIMITED . If it can’t be determined it is set to psutil.POWER_TIME_UNKNOWN .
  • power_plugged: True if the AC power cable is connected, False if not or None if it can’t be determined.

See also battery.py and sensors.py for an example application.

Availability: Linux, Windows, FreeBSD

New in version 5.1.0.

Changed in version 5.4.2: added macOS support

Other system info¶

Return the system boot time expressed in seconds since the epoch. Example:

on Windows this function may return a time which is off by 1 second if it’s used across different processes (see issue #1007).

Return users currently connected on the system as a list of named tuples including the following fields:

  • name: the name of the user.
  • terminal: the tty or pseudo-tty associated with the user, if any, else None .
  • host: the host name associated with the entry, if any.
  • started: the creation time as a floating point number expressed in seconds since the epoch.
  • pid: the PID of the login process (like sshd, tmux, gdm-session-worker, …). On Windows and OpenBSD this is always set to None .

Changed in version 5.3.0: added “pid” field

Processes¶

Functions¶

Return a sorted list of current running PIDs. To iterate over all processes and avoid race conditions process_iter() should be preferred.

Changed in version 5.6.0: PIDs are returned in sorted order

Return an iterator yielding a Process class instance for all running processes on the local machine. This should be preferred over psutil.pids() to iterate over processes as it’s safe from race condition.

Every Process instance is only created once, and then cached for the next time psutil.process_iter() is called (if PID is still alive). Also it makes sure process PIDs are not reused.

attrs and ad_value have the same meaning as in Process.as_dict() . If attrs is specified Process.as_dict() result will be stored as a info attribute attached to the returned Process instances. If attrs is an empty list it will retrieve all process info (slow).

Sorting order in which processes are returned is based on their PID.

A dict comprehensions to create a data structure:

Changed in version 5.3.0: added “attrs” and “ad_value” parameters.

Check whether the given PID exists in the current process list. This is faster than doing pid in psutil.pids() and should be preferred.

psutil. wait_procs ( procs, timeout=None, callback=None ) ¶

Convenience function which waits for a list of Process instances to terminate. Return a (gone, alive) tuple indicating which processes are gone and which ones are still alive. The gone ones will have a new returncode attribute indicating process exit status as returned by Process.wait() . callback is a function which gets called when one of the processes being waited on is terminated and a Process instance is passed as callback argument (the instance will also have a returncode attribute set). This function will return as soon as all processes terminate or when timeout (seconds) occurs. Differently from Process.wait() it will not raise TimeoutExpired if timeout occurs. A typical use case may be:

  • send SIGTERM to a list of processes
  • give them some time to terminate
  • send SIGKILL to those ones which are still alive

Example which terminates and waits all the children of this process:

Exceptions¶

Base exception class. All other exceptions inherit from this one.

class psutil. NoSuchProcess ( pid, name=None, msg=None ) ¶

Raised by Process class methods when no process with the given pid is found in the current process list, or when a process no longer exists. name is the name the process had before disappearing and gets set only if Process.name() was previously called.

class psutil. ZombieProcess ( pid, name=None, ppid=None, msg=None ) ¶

This may be raised by Process class methods when querying a zombie process on UNIX (Windows doesn’t have zombie processes). name and ppid attributes are available if Process.name() or Process.ppid() methods were called before the process turned into a zombie.

this is a subclass of NoSuchProcess so if you’re not interested in retrieving zombies (e.g. when using process_iter() ) you can ignore this exception and just catch NoSuchProcess .

New in version 3.0.0.

Raised by Process class methods when permission to perform an action is denied due to insufficient privileges. name attribute is available if Process.name() was previously called.

class psutil. TimeoutExpired ( seconds, pid=None, name=None, msg=None ) ¶

Raised by Process.wait() method if timeout expires and the process is still alive. name attribute is available if Process.name() was previously called.

Process class¶

Represents an OS process with the given pid. If pid is omitted current process pid (os.getpid) is used. Raise NoSuchProcess if pid does not exist. On Linux pid can also refer to a thread ID (the id field returned by threads() method). When accessing methods of this class always be prepared to catch NoSuchProcess and AccessDenied exceptions. hash builtin can be used against instances of this class in order to identify a process univocally over time (the hash is determined by mixing process PID + creation time). As such it can also be used with set.

In order to efficiently fetch more than one information about the process at the same time, make sure to use either oneshot() context manager or as_dict() utility method.

the way this class is bound to a process is uniquely via its PID. That means that if the process terminates and the OS reuses its PID you may end up interacting with another process. The only exceptions for which process identity is preemptively checked (via PID + creation time) is for the following methods: nice() (set), ionice() (set), cpu_affinity() (set), rlimit() (set), children() , parent() , parents() , suspend() resume() , send_signal() , terminate() kill() . To prevent this problem for all other methods you can use is_running() before querying the process or process_iter() in case you’re iterating over all processes. It must be noted though that unless you deal with very “old” (inactive) Process instances this will hardly represent a problem.

Utility context manager which considerably speeds up the retrieval of multiple process information at the same time. Internally different process info (e.g. name() , ppid() , uids() , create_time() , …) may be fetched by using the same routine, but only one value is returned and the others are discarded. When using this context manager the internal routine is executed once (in the example below on name() ) the value of interest is returned and the others are cached. The subsequent calls sharing the same internal routine will return the cached value. The cache is cleared when exiting the context manager block. The advice is to use this every time you retrieve more than one information about the process. If you’re lucky, you’ll get a hell of a speedup. Example:

Here’s a list of methods which can take advantage of the speedup depending on what platform you’re on. In the table below horizontal empty rows indicate what process methods can be efficiently grouped together internally. The last column (speedup) shows an approximation of the speedup you can get if you call all the methods together (best case scenario).

Linux Windows macOS BSD SunOS AIX
cpu_num() cpu_percent() cpu_percent() cpu_num() name() name()
cpu_percent() cpu_times() cpu_times() cpu_percent() cmdline() cmdline()
cpu_times() io_counters() memory_info() cpu_times() create_time() create_time()
create_time() memory_info() memory_percent() create_time()
name() memory_maps() num_ctx_switches() gids() memory_info() memory_info()
ppid() num_ctx_switches() num_threads() io_counters() memory_percent() memory_percent()
status() num_handles() name() num_threads() num_threads()
terminal() num_threads() create_time() memory_info() ppid() ppid()
username() gids() memory_percent() status() status()
gids() name() num_ctx_switches() terminal() terminal()
num_ctx_switches() exe() ppid() ppid()
num_threads() name() status() status() gids() gids()
uids() terminal() terminal() uids() uids()
username() uids() uids() username() username()
username() username()
memory_full_info()
memory_maps()
speedup: +2.6x speedup: +1.8x / +6.5x speedup: +1.9x speedup: +2.0x speedup: +1.3x speedup: +1.3x

New in version 5.0.0.

The process PID. This is the only (read-only) attribute of the class.

The process parent PID. On Windows the return value is cached after first call. Not on POSIX because ppid may change if process becomes a zombie See also parent() and parents() methods.

The process name. On Windows the return value is cached after first call. Not on POSIX because the process name may change. See also how to find a process by name.

The process executable as an absolute path. On some systems this may also be an empty string. The return value is cached after first call.

The command line this process has been called with as a list of strings. The return value is not cached because the cmdline of a process may change.

The environment variables of the process as a dict. Note: this might not reflect changes made after the process started.

on macOS Big Sur this function returns something meaningful only for the current process or in other specific circumstances).

New in version 4.0.0.

Changed in version 5.3.0: added SunOS support

Changed in version 5.6.3: added AIX support

Changed in version 5.7.3: added BSD support

The process creation time as a floating point number expressed in seconds since the epoch. The return value is cached after first call.

Utility method retrieving multiple process information as a dictionary. If attrs is specified it must be a list of strings reflecting available Process class’s attribute names. Here’s a list of possible string values: ‘cmdline’ , ‘connections’ , ‘cpu_affinity’ , ‘cpu_num’ , ‘cpu_percent’ , ‘cpu_times’ , ‘create_time’ , ‘cwd’ , ‘environ’ , ‘exe’ , ‘gids’ , ‘io_counters’ , ‘ionice’ , ‘memory_full_info’ , ‘memory_info’ , ‘memory_maps’ , ‘memory_percent’ , ‘name’ , ‘nice’ , ‘num_ctx_switches’ , ‘num_fds’ , ‘num_handles’ , ‘num_threads’ , ‘open_files’ , ‘pid’ , ‘ppid’ , ‘status’ , ‘terminal’ , ‘threads’ , ‘uids’ , ‘username’` . If attrs argument is not passed all public read only attributes are assumed. ad_value is the value which gets assigned to a dict key in case AccessDenied or ZombieProcess exception is raised when retrieving that particular process information. Internally, as_dict() uses oneshot() context manager so there’s no need you use it also.

Changed in version 3.0.0: ad_value is used also when incurring into ZombieProcess exception, not only AccessDenied

Changed in version 4.5.0: as_dict() is considerably faster thanks to oneshot() context manager.

Utility method which returns the parent process as a Process object, preemptively checking whether PID has been reused. If no parent PID is known return None . See also ppid() and parents() methods.

Utility method which return the parents of this process as a list of Process instances. If no parents are known return an empty list. See also ppid() and parent() methods.

New in version 5.6.0.

The current process status as a string. The returned string is one of the psutil.STATUS_* constants.

The process current working directory as an absolute path.

Changed in version 5.6.4: added support for NetBSD

The name of the user that owns the process. On UNIX this is calculated by using real process uid.

The real, effective and saved user ids of this process as a named tuple. This is the same as os.getresuid but can be used for any process PID.

The real, effective and saved group ids of this process as a named tuple. This is the same as os.getresgid but can be used for any process PID.

The terminal associated with this process, if any, else None . This is similar to “tty” command but can be used for any process PID.

Get or set process niceness (priority). On UNIX this is a number which usually goes from -20 to 20 . The higher the nice value, the lower the priority of the process.

Starting from Python 3.3 this functionality is also available as os.getpriority and os.setpriority (see BPO-10784). On Windows this is implemented via GetPriorityClass and SetPriorityClass Windows APIs and value is one of the psutil.*_PRIORITY_CLASS constants reflecting the MSDN documentation. Example which increases process priority on Windows:

Get or set process I/O niceness (priority). If no argument is provided it acts as a get, returning a (ioclass, value) tuple on Linux and a ioclass integer on Windows. If ioclass is provided it acts as a set. In this case an additional value can be specified on Linux only in order to increase or decrease the I/O priority even further. Here’s the possible platform-dependent ioclass values.

Linux (see ioprio_get manual):

  • IOPRIO_CLASS_RT : (high) the process gets first access to the disk every time. Use it with care as it can starve the entire system. Additional priority level can be specified and ranges from 0 (highest) to 7 (lowest).
  • IOPRIO_CLASS_BE : (normal) the default for any process that hasn’t set a specific I/O priority. Additional priority level ranges from 0 (highest) to 7 (lowest).
  • IOPRIO_CLASS_IDLE : (low) get I/O time when no-one else needs the disk. No additional value is accepted.
  • IOPRIO_CLASS_NONE : returned when no priority was previously set.
  • IOPRIO_HIGH : highest priority.
  • IOPRIO_NORMAL : default priority.
  • IOPRIO_LOW : low priority.
  • IOPRIO_VERYLOW : lowest priority.

Here’s an example on how to set the highest I/O priority depending on what platform you’re on:

Availability: Linux, Windows Vista+

Changed in version 5.6.2: Windows accepts new IOPRIO_* constants including new IOPRIO_HIGH .

Get or set process resource limits (see man prlimit). resource is one of the psutil.RLIMIT_* constants. limits is a (soft, hard) tuple. This is the same as resource.getrlimit and resource.setrlimit but can be used for any process PID, not only os.getpid. For get, return value is a (soft, hard) tuple. Each value may be either and integer or psutil.RLIMIT_* . Example:

Also see procinfo.py script.

Availability: Linux, FreeBSD

Changed in version 5.7.3: added FreeBSD support

Return process I/O statistics as a named tuple. For Linux you can refer to /proc filesystem documentation.

  • read_count: the number of read operations performed (cumulative). This is supposed to count the number of read-related syscalls such as read() and pread() on UNIX.
  • write_count: the number of write operations performed (cumulative). This is supposed to count the number of write-related syscalls such as write() and pwrite() on UNIX.
  • read_bytes: the number of bytes read (cumulative). Always -1 on BSD.
  • write_bytes: the number of bytes written (cumulative). Always -1 on BSD.
  • read_chars(Linux): the amount of bytes which this process passed to read() and pread() syscalls (cumulative). Differently from read_bytes it doesn’t care whether or not actual physical disk I/O occurred.
  • write_chars(Linux): the amount of bytes which this process passed to write() and pwrite() syscalls (cumulative). Differently from write_bytes it doesn’t care whether or not actual physical disk I/O occurred.
  • other_count(Windows): the number of I/O operations performed other than read and write operations.
  • other_bytes(Windows): the number of bytes transferred during operations other than read and write operations.

Availability: Linux, BSD, Windows, AIX

Changed in version 5.2.0: added read_chars and write_chars on Linux; added other_count and other_bytes on Windows.

The number voluntary and involuntary context switches performed by this process (cumulative).

Changed in version 5.4.1: added AIX support

The number of file descriptors currently opened by this process (non cumulative).

The number of handles currently used by this process (non cumulative).

The number of threads currently used by this process (non cumulative).

Return threads opened by process as a list of named tuples. On OpenBSD this method requires root privileges.

  • id: the native thread ID assigned by the kernel. If pid refers to the current process, this matches the native_id attribute of the threading.Thread class, and can be used to reference individual Python threads running within your own Python app.
  • user_time: time spent in user mode.
  • system_time: time spent in kernel mode.

cpu_times ( ) ¶

Return a named tuple representing the accumulated process times, in seconds (see explanation). This is similar to os.times but can be used for any process PID.

  • user: time spent in user mode.
  • system: time spent in kernel mode.
  • children_user: user time of all child processes (always 0 on Windows and macOS).
  • children_system: system time of all child processes (always 0 on Windows and macOS).
  • iowait: (Linux) time spent waiting for blocking I/O to complete. This value is excluded from user and system times count (because the CPU is not doing any work).

Changed in version 4.1.0: return two extra fields: children_user and children_system.

Changed in version 5.6.4: added iowait on Linux.

Return a float representing the process CPU utilization as a percentage which can also be > 100.0 in case of a process running multiple threads on different CPUs. When interval is > 0.0 compares process times to system CPU times elapsed before and after the interval (blocking). When interval is 0.0 or None compares process times to system CPU times elapsed since last call, returning immediately. That means the first time this is called it will return a meaningless 0.0 value which you are supposed to ignore. In this case is recommended for accuracy that this function be called a second time with at least 0.1 seconds between calls. Example:

the returned value can be > 100.0 in case of a process running multiple threads on different CPU cores.

the returned value is explicitly not split evenly between all available CPUs (differently from psutil.cpu_percent() ). This means that a busy loop process running on a system with 2 logical CPUs will be reported as having 100% CPU utilization instead of 50%. This was done in order to be consistent with top UNIX utility and also to make it easier to identify processes hogging CPU resources independently from the number of CPUs. It must be noted that taskmgr.exe on Windows does not behave like this (it would report 50% usage instead). To emulate Windows taskmgr.exe behavior you can do: p.cpu_percent() / psutil.cpu_count() .

the first time this method is called with interval = 0.0 or None it will return a meaningless 0.0 value which you are supposed to ignore.

Get or set process current CPU affinity. CPU affinity consists in telling the OS to run a process on a limited set of CPUs only (on Linux cmdline, taskset command is typically used). If no argument is passed it returns the current CPU affinity as a list of integers. If passed it must be a list of integers specifying the new CPUs affinity. If an empty list is passed all eligible CPUs are assumed (and set). On some systems such as Linux this may not necessarily mean all available logical CPUs as in list(range(psutil.cpu_count())) ).

Availability: Linux, Windows, FreeBSD

Changed in version 2.2.0: added support for FreeBSD

Changed in version 5.1.0: an empty list can be passed to set affinity against all eligible CPUs.

Return what CPU this process is currently running on. The returned number should be psutil.cpu_count() . On FreeBSD certain kernel process may return -1 . It may be used in conjunction with psutil.cpu_percent(percpu=True) to observe the system workload distributed across multiple CPUs as shown by cpu_distribution.py example script.

Availability: Linux, FreeBSD, SunOS

New in version 5.1.0.

Return a named tuple with variable fields depending on the platform representing memory information about the process. The “portable” fields available on all platforms are rss and vms . All numbers are expressed in bytes.

Linux macOS BSD Solaris AIX Windows
rss rss rss rss rss rss (alias for wset )
vms vms vms vms vms vms (alias for pagefile )
shared pfaults text num_page_faults
text pageins data peak_wset
lib stack wset
data peak_paged_pool
dirty paged_pool
peak_nonpaged_pool
nonpaged_pool
pagefile
peak_pagefile
private
  • rss: aka “Resident Set Size”, this is the non-swapped physical memory a process has used. On UNIX it matches “top“‘s RES column). On Windows this is an alias for wset field and it matches “Mem Usage” column of taskmgr.exe.
  • vms: aka “Virtual Memory Size”, this is the total amount of virtual memory used by the process. On UNIX it matches “top“‘s VIRT column. On Windows this is an alias for pagefile field and it matches “Mem Usage” “VM Size” column of taskmgr.exe.
  • shared: (Linux) memory that could be potentially shared with other processes. This matches “top“‘s SHR column).
  • text(Linux, BSD): aka TRS (text resident set) the amount of memory devoted to executable code. This matches “top“‘s CODE column).
  • data(Linux, BSD): aka DRS (data resident set) the amount of physical memory devoted to other than executable code. It matches “top“‘s DATA column).
  • lib(Linux): the memory used by shared libraries.
  • dirty(Linux): the number of dirty pages.
  • pfaults(macOS): number of page faults.
  • pageins(macOS): number of actual pageins.

For on explanation of Windows fields rely on PROCESS_MEMORY_COUNTERS_EX structure doc. Example on Linux:

Changed in version 4.0.0: multiple fields are returned, not only rss and vms .

deprecated in version 4.0.0; use memory_info() instead.

This method returns the same information as memory_info() , plus, on some platform (Linux, macOS, Windows), also provides additional metrics (USS, PSS and swap). The additional metrics provide a better representation of “effective” process memory consumption (in case of USS) as explained in detail in this blog post. It does so by passing through the whole process address. As such it usually requires higher user privileges than memory_info() and is considerably slower. On platforms where extra fields are not implemented this simply returns the same metrics as memory_info() .

  • uss(Linux, macOS, Windows): aka “Unique Set Size”, this is the memory which is unique to a process and which would be freed if the process was terminated right now.
  • pss(Linux): aka “Proportional Set Size”, is the amount of memory shared with other processes, accounted in a way that the amount is divided evenly between the processes that share it. I.e. if a process has 10 MBs all to itself and 10 MBs shared with another process its PSS will be 15 MBs.
  • swap(Linux): amount of memory that has been swapped out to disk.

uss is probably the most representative metric for determining how much memory is actually being used by a process. It represents the amount of memory that would be freed if the process was terminated right now.

Example on Linux:

See also procsmem.py for an example application.

New in version 4.0.0.

Compare process memory to total physical system memory and calculate process memory utilization as a percentage. memtype argument is a string that dictates what type of process memory you want to compare against. You can choose between the named tuple field names returned by memory_info() and memory_full_info() (defaults to «rss» ).

Changed in version 4.0.0: added memtype parameter.

Return process’s mapped memory regions as a list of named tuples whose fields are variable depending on the platform. This method is useful to obtain a detailed representation of process memory usage as explained here (the most important value is “private” memory). If grouped is True the mapped regions with the same path are grouped together and the different memory fields are summed. If grouped is False each mapped region is shown as a single entity and the named tuple will also include the mapped region’s address space (addr) and permission set (perms). See pmap.py for an example application.

Linux Windows FreeBSD Solaris
rss rss rss rss
size private anonymous
pss ref_count locked
shared_clean shadow_count
shared_dirty
private_clean
private_dirty
referenced
anonymous
swap

Availability: Linux, Windows, FreeBSD, SunOS

Changed in version 5.6.0: removed macOS support because inherently broken (see issue #1291)

Return the children of this process as a list of Process instances. If recursive is True return all the parent descendants. Pseudo code example assuming A == this process:

Note that in the example above if process X disappears process Y won’t be returned either as the reference to process A is lost. This concept is well summaried by this unit test. See also how to kill a process tree and terminate my children.

Return regular files opened by process as a list of named tuples including the following fields:

  • path: the absolute file name.
  • fd: the file descriptor number; on Windows this is always -1 .
  • position (Linux): the file (offset) position.
  • mode (Linux): a string indicating how the file was opened, similarly to open builtin mode argument. Possible values are ‘r’ , ‘w’ , ‘a’ , ‘r+’ and ‘a+’ . There’s no distinction between files opened in binary or text mode ( «b» or «t» ).
  • flags (Linux): the flags which were passed to the underlying os.open C call when the file was opened (e.g. os.O_RDONLY, os.O_TRUNC, etc).

on Windows this method is not reliable due to some limitations of the underlying Windows API which may hang when retrieving certain file handles. In order to work around that psutil spawns a thread to determine the file handle name and kills it if it’s not responding after 100ms. That implies that this method on Windows is not guaranteed to enumerate all regular file handles (see issue 597). Tools like ProcessHacker has the same limitation.

on BSD this method can return files with a null path (“”) due to a kernel bug, hence it’s not reliable (see issue 595).

Changed in version 3.1.0: no longer hangs on Windows.

Changed in version 4.1.0: new position, mode and flags fields on Linux.

Return socket connections opened by process as a list of named tuples. To get system-wide connections use psutil.net_connections() . Every named tuple provides 6 attributes:

  • fd: the socket file descriptor. This can be passed to socket.fromfd to obtain a usable socket object. On Windows, FreeBSD and SunOS this is always set to -1 .
  • family: the address family, either AF_INET, AF_INET6 or AF_UNIX.
  • type: the address type, either SOCK_STREAM, SOCK_DGRAM or SOCK_SEQPACKET. .
  • laddr: the local address as a (ip, port) named tuple or a path in case of AF_UNIX sockets. For UNIX sockets see notes below.
  • raddr: the remote address as a (ip, port) named tuple or an absolute path in case of UNIX sockets. When the remote endpoint is not connected you’ll get an empty tuple (AF_INET*) or «» (AF_UNIX). For UNIX sockets see notes below.
  • status: represents the status of a TCP connection. The return value is one of the psutil.CONN_* constants. For UDP and UNIX sockets this is always going to be psutil.CONN_NONE .

The kind parameter is a string which filters for connections that fit the following 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

(Solaris) UNIX sockets are not supported.

(Linux, FreeBSD) “raddr” field for UNIX sockets is always set to “”. This is a limitation of the OS.

(OpenBSD) “laddr” and “raddr” fields for UNIX sockets are always set to “”. This is a limitation of the OS.

(AIX) psutil.AccessDenied is always raised unless running as root (lsof does the same).

Changed in version 5.3.0: : “laddr” and “raddr” are named tuples.

Return whether the current process is running in the current process list. This is reliable also in case the process is gone and its PID reused by another process, therefore it must be preferred over doing psutil.pid_exists(p.pid) .

this will return True also if the process is a zombie ( p.status() == psutil.STATUS_ZOMBIE ).

Send a signal to process (see signal module constants) preemptively checking whether PID has been reused. On UNIX this is the same as os.kill(pid, sig) . On Windows only SIGTERM, CTRL_C_EVENT and CTRL_BREAK_EVENT signals are supported and SIGTERM is treated as an alias for kill() . See also how to kill a process tree and terminate my children.

Changed in version 3.2.0: support for CTRL_C_EVENT and CTRL_BREAK_EVENT signals on Windows was added.

Suspend process execution with SIGSTOP signal preemptively checking whether PID has been reused. On UNIX this is the same as os.kill(pid, signal.SIGSTOP) . On Windows this is done by suspending all process threads execution.

Resume process execution with SIGCONT signal preemptively checking whether PID has been reused. On UNIX this is the same as os.kill(pid, signal.SIGCONT) . On Windows this is done by resuming all process threads execution.

Terminate the process with SIGTERM signal preemptively checking whether PID has been reused. On UNIX this is the same as os.kill(pid, signal.SIGTERM) . On Windows this is an alias for kill() . See also how to kill a process tree and terminate my children.

Kill the current process by using SIGKILL signal preemptively checking whether PID has been reused. On UNIX this is the same as os.kill(pid, signal.SIGKILL) . On Windows this is done by using TerminateProcess. See also how to kill a process tree and terminate my children.

Wait for a process PID to terminate. The details about the return value differ on UNIX and Windows.

On UNIX: if the process terminated normally, the return value is a positive integer >= 0 indicating the exit code. If the process was terminated by a signal return the negated value of the signal which caused the termination (e.g. -SIGTERM ). If PID is not a children of os.getpid (current process) just wait until the process disappears and return None . If PID does not exist return None immediately.

On Windows: always return the exit code, which is a positive integer as returned by GetExitCodeProcess.

timeout is expressed in seconds. If specified and the process is still alive raise TimeoutExpired exception. timeout=0 can be used in non-blocking apps: it will either return immediately or raise TimeoutExpired .

The return value is cached. To wait for multiple processes use psutil.wait_procs() .

Changed in version 5.7.1: return value is cached (instead of returning None ).

Changed in version 5.7.1: on POSIX, in case of negative signal, return it as a human readable enum.

Same as subprocess.Popen but in addition it provides all psutil.Process methods in a single class. For the following methods which are common to both classes, psutil implementation takes precedence: send_signal() , terminate() , kill() . This is done in order to avoid killing another process in case its PID has been reused, fixing BPO-6973.

Changed in version 4.4.0: added context manager support

Windows services¶

Return an iterator yielding a WindowsService class instance for all Windows services installed.

New in version 4.2.0.

psutil. win_service_get ( name ) ¶

Get a Windows service by name, returning a WindowsService instance. Raise psutil.NoSuchProcess if no service with such name exists.

New in version 4.2.0.

class psutil. WindowsService ¶

Represents a Windows service with the given name. This class is returned by win_service_iter() and win_service_get() functions and it is not supposed to be instantiated directly.

The service name. This string is how a service is referenced and can be passed to win_service_get() to get a new WindowsService instance.

The service display name. The value is cached when this class is instantiated.

The fully qualified path to the service binary/exe file as a string, including command line arguments.

The name of the user that owns this service.

A string which can either be “automatic” , “manual” or “disabled” .

The process PID, if any, else None . This can be passed to Process class to control the service’s process.

Service status as a string, which may be either “running” , “paused” , “start_pending” , “pause_pending” , “continue_pending” , “stop_pending” or “stopped” .

Service long description.

Utility method retrieving all the information above as a dictionary.

Источник

Check the temperature of your CPU using Python (and other cool tricks)

by Ori Roza

rEV20g78X3XQH2m7m4rtBX5VkdwfzhnvUXg9

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]: {'ACPI\ThermalZone\THM0_0':         [shwtemp(label='',          current=49.05000000000001,          high=127.05000000000001,          critical=127.05000000000001)]}

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 [2]: p.cpu_percent()Out[2]: 0.0
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.

Let’s check the output.

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?


Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Материал содержит описание функций модуля psutil с примерами, которые считывают и возвращают информацию с датчиков сервера, таких как температура оборудования (процессор, HDD и т.д.), скорость вентиляторов, статус и заряд батареи.

Содержание:

  • psutil.sensors_temperatures() показания температуры оборудования,
  • psutil.sensors_fans() скорость аппаратных вентиляторов,
  • psutil.sensors_battery() информация о состоянии батареи,
  • Пример измерения температуры оборудования,
  • Пример извлечения скорости вентиляторов и информации о батарее.

psutil.sensors_temperatures(fahrenheit=False):

Функция psutil.sensors_temperatures() возвращает показания температуры оборудования. Каждая запись — это именованный кортеж, представляющий определенный аппаратный датчик температуры (это может быть процессор, жесткий диск или что-то еще, в зависимости от ОС и ее конфигурации).

Все температуры выражаются в градусах Цельсия, если для аргумента fahrenheit не установлено значение True. Если датчики не поддерживаются ОС, возвращается пустой словарь.

Пример использования psutil.sensors_temperatures():

>>> import psutil
>>> psutil.sensors_temperatures()
# {'acpitz': [shwtemp(label='', current=47.0, high=103.0, critical=103.0)],
#  'asus': [shwtemp(label='', current=47.0, high=None, critical=None)],
#  'coretemp': [shwtemp(label='Physical id 0', current=52.0, high=100.0, critical=100.0),
#               shwtemp(label='Core 0', current=45.0, high=100.0, critical=100.0),
#               shwtemp(label='Core 1', current=52.0, high=100.0, critical=100.0),
#               shwtemp(label='Core 2', current=45.0, high=100.0, critical=100.0),
#               shwtemp(label='Core 3', current=47.0, high=100.0, critical=100.0)]}

Доступность: Linux, FreeBSD

psutil.sensors_fans():

Функция psutil.sensors_fans() возвращает скорость аппаратных вентиляторов. Каждая запись представляет собой именованный кортеж, представляющий определенный вентилятор аппаратного датчика.

Скорость вентилятора выражается в RPM (оборотов в минуту). Если датчики не поддерживаются ОС, возвращается пустой словарь.

Пример использования psutil.sensors_fans():

>>> import psutil
>>> psutil.sensors_fans()
# {'asus': [sfan(label='cpu_fan', current=3200)]}

Доступность: Linux

psutil.sensors_battery():

Функция psutil.sensors_battery() возвращает информацию о состоянии батареи в виде именованного кортежа, включая следующие значения. Если батарея не установлена ​​или метрики не могут быть определены, возвращается None.

  • percent: battery power left as a percentage.
  • secsleft: a rough approximation of how many seconds are left before the battery runs out of power. If the AC power cable is connected this is set to -psutil.POWERTIMEUNLIMITED. If it can’t be determined it is set to psutil.POWERTIMEUNKNOWN.
  • `power_plugged: True if the AC power cable is connected, False if not or None if it can’t be determined.

Пример использования psutil.sensors_battery():

>>> import psutil
>>> def secs2hours(secs):
...     mm, ss = divmod(secs, 60)
...     hh, mm = divmod(mm, 60)
...     return "%d:%02d:%02d" % (hh, mm, ss)

>>> battery = psutil.sensors_battery()
>>> battery
# sbattery(percent=93, secsleft=16628, power_plugged=False)
>>> print("charge = %s%%, time left = %s" % (battery.percent, secs2hours(battery.secsleft)))
# charge = 93%, time left = 4:37:08

Доступность: Linux, Windows, FreeBSD

Пример измерения температуры оборудования.

Пример представляет простенький сценарий для измерения температуры оборудования в Linux.

import sys
import psutil

def main():
    if not hasattr(psutil, "sensors_temperatures"):
        sys.exit("платформа не поддерживается")
    temps = psutil.sensors_temperatures()
    if not temps:
        sys.exit("не могу определить никакую температуру")
    for name, entries in temps.items():
        print(name)
        for entry in entries:
            print("    %-20s %s °C (high = %s °C, critical = %s °C)" % (
                entry.label or name, entry.current, entry.high,
                entry.critical))
        print()

if __name__ == '__main__':
    main()

Вывод сценария:

$ python3 test.py
asus
    asus                 47.0 °C (high = None °C, critical = None °C)
acpitz
    acpitz               47.0 °C (high = 103.0 °C, critical = 103.0 °C)
coretemp
    Physical id 0        54.0 °C (high = 100.0 °C, critical = 100.0 °C)
    Core 0               47.0 °C (high = 100.0 °C, critical = 100.0 °C)
    Core 1               48.0 °C (high = 100.0 °C, critical = 100.0 °C)
    Core 2               47.0 °C (high = 100.0 °C, critical = 100.0 °C)
    Core 3               54.0 °C (high = 100.0 °C, critical = 100.0 °C)

Пример извлечения скорости вентиляторов и информации о батарее.

Этот пример представляет собой клон утилиты «sensors» для измерения температуры оборудования в Linux, скорости вентиляторов и извлечения информации о батарее.

import psutil

def secs2hours(secs):
    mm, ss = divmod(secs, 60)
    hh, mm = divmod(mm, 60)
    return "%d:%02d:%02d" % (hh, mm, ss)

def main():
    if hasattr(psutil, "sensors_temperatures"):
        temps = psutil.sensors_temperatures()
    else:
        temps = {}
    if hasattr(psutil, "sensors_fans"):
        fans = psutil.sensors_fans()
    else:
        fans = {}
    if hasattr(psutil, "sensors_battery"):
        battery = psutil.sensors_battery()
    else:
        battery = None

    if not any((temps, fans, battery)):
        print("не удается прочитать информацию "
              "о температуре, вентиляторах или батарее")
        return

    names = set(list(temps.keys()) + list(fans.keys()))
    for name in names:
        print(name)
        # температура.
        if name in temps:
            print("    Temperatures:")
            for entry in temps[name]:
                print("        %-20s %s°C (high=%s°C, critical=%s°C)" % (
                    entry.label or name, entry.current, entry.high,
                    entry.critical))
        # вентиляторы.
        if name in fans:
            print("    Fans:")
            for entry in fans[name]:
                print("        %-20s %s RPM" % (
                    entry.label or name, entry.current))

    # батарея.
    if battery:
        print("Battery:")
        print("    charge:     %s%%" % round(battery.percent, 2))
        if battery.power_plugged:
            print("    status:     %s" % (
                "charging" if battery.percent < 100 else "fully charged"))
            print("    plugged in: yes")
        else:
            print("    left:       %s" % secs2hours(battery.secsleft))
            print("    status:     %s" % "discharging")
            print("    plugged in: no")


if __name__ == '__main__':
    main()

Вывод сценария:

$ python3 test.py
asus
    Temperatures:
        asus                 57.0°C (high=None°C, critical=None°C)
    Fans:
        cpu_fan              3500 RPM
acpitz
    Temperatures:
        acpitz               57.0°C (high=108.0°C, critical=108.0°C)
coretemp
    Temperatures:
        Physical id 0        61.0°C (high=87.0°C, critical=105.0°C)
        Core 0               61.0°C (high=87.0°C, critical=105.0°C)
        Core 1               59.0°C (high=87.0°C, critical=105.0°C)
Battery:
    charge:     84.95%
    status:     charging
    plugged in: yes

Project description

Script for checking current CPU temperature or
average temperature in given time period.

You can get it by downloading it directly or by typing:

$ pip install CPU-temperature-monitor

After it is installed you can check your current temperature by running:

$ get_current_cpu_temp

Or in case of expected excessive work of CPU, it is possible to monitor
CPU temperature in given time frame, after which you can find average value
of CPU temperature, inside a ‘average_cpu_temperature.txt’ file.

If temperature went over it’s upper limit and reached critical level alert
sound will be raised and additional details will be stored in ‘critical_temperature_occurrences.txt’
file.

$ get_average_cpu_temp 'integer value representing number of hours' 'integer value representing number of minutes'

Download files

Download the file for your platform. If you’re not sure which to choose, learn more about installing packages.

Source Distribution

Понравилась статья? Поделить с друзьями:
  • Как узнать температуру процессора в windows 10 powershell
  • Как узнать температуру процессора в windows 10 cmd
  • Как узнать температуру процессора windows 10 cpu z
  • Как узнать температуру оперативной памяти в windows 10
  • Как узнать скорость hdd windows 10