程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python中一個非常強大的第三方庫-psutil

編輯:Python

psutil是一個非常強大的第三方庫,用法簡單,這裡主要是做一下梳理。

先看看官方說明:

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是一個跨平台庫,可以獲取系統硬件利用率(包括CPU, memory, disks, network, sensors)和正在運行的進程的信息。主要用於系統資源監控和進程管理。

安裝psutil:

# pip3 install psutil
>>> import psutil
>>> dir(psutil)
['AF_LINK', 'AIX', 'AccessDenied', 'BSD', 'CONN_CLOSE', 'CONN_CLOSE_WAIT', 'CONN_CLOSING', 'CONN_ESTABLISHED', 'CONN_FIN_WAIT1', 'CONN_FIN_WAIT2', 'CONN_LAST_ACK', 'CONN_LISTEN', 'CONN_NONE', 'CONN_SYN_RECV', 'CONN_SYN_SENT', 'CONN_TIME_WAIT', 'Error', 'FREEBSD', 'IOPRIO_CLASS_BE', 'IOPRIO_CLASS_IDLE', 'IOPRIO_CLASS_NONE', 'IOPRIO_CLASS_RT', 'LINUX', 'NETBSD', 'NIC_DUPLEX_FULL', 'NIC_DUPLEX_HALF', 'NIC_DUPLEX_UNKNOWN', 'NoSuchProcess', 'OPENBSD', 'OSX', 'POSIX', 'POWER_TIME_UNKNOWN', 'POWER_TIME_UNLIMITED', 'PROCFS_PATH', 'Popen', 'Process', 'RLIMIT_AS', 'RLIMIT_CORE', 'RLIMIT_CPU', 'RLIMIT_DATA', 'RLIMIT_FSIZE', 'RLIMIT_LOCKS', 'RLIMIT_MEMLOCK', 'RLIMIT_MSGQUEUE', 'RLIMIT_NICE', 'RLIMIT_NOFILE', 'RLIMIT_NPROC', 'RLIMIT_RSS', 'RLIMIT_RTPRIO', 'RLIMIT_RTTIME', 'RLIMIT_SIGPENDING', 'RLIMIT_STACK', 'RLIM_INFINITY', 'STATUS_DEAD', 'STATUS_DISK_SLEEP', 'STATUS_IDLE', 'STATUS_LOCKED', 'STATUS_RUNNING', 'STATUS_SLEEPING', 'STATUS_STOPPED', 'STATUS_TRACING_STOP', 'STATUS_WAITING', 'STATUS_WAKING', 'STATUS_ZOMBIE', 'SUNOS', 'TimeoutExpired', 'WINDOWS', 'ZombieProcess', '_PY3', '_TOTAL_PHYMEM', '__all__', '__author__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', '_as_dict_attrnames', '_assert_pid_not_reused', '_common', '_compat', '_cpu_busy_time', '_cpu_tot_time', '_last_cpu_times', '_last_cpu_times_2', '_last_per_cpu_times', '_last_per_cpu_times_2', '_pmap', '_pslinux', '_psplatform', '_psposix', '_psutil_linux', '_psutil_posix', '_timer', '_wrap_numbers', 'boot_time', 'callable', 'collections', 'contextlib', 'cpu_count', 'cpu_percent', 'cpu_stats', 'cpu_times', 'cpu_times_percent', 'disk_io_counters', 'disk_partitions', 'disk_usage', 'errno', 'functools', 'long', 'net_connections', 'net_if_addrs', 'net_if_stats', 'net_io_counters', 'os', 'pid_exists', 'pids', 'process_iter', 'pwd', 'sensors_battery', 'sensors_fans', 'sensors_temperatures', 'signal', 'subprocess', 'swap_memory', 'sys', 'test', 'time', 'traceback', 'users', 'version_info', 'virtual_memory', 'wait_procs']

用法如下:

CPU

psutil.cpu_times(percpu=False)
psutil.cpu_percent(interval=None, percpu=False)
psutil.cpu_times_percent(interval=None, percpu=False)
psutil.cpu_stats()
psutil.cpu_freq(percpu=False)
psutil.cpu_count(logical=True):獲取CPU個數或核心數。
Return the number of logical CPUs in the system (same as os.cpu_count() in Python 3.4) or None if undetermined.
This number may not be equivalent to the number of CPUs the current process can actually use in case process CPU affinity has been changed or Linux cgroups are being used.
The number of usable CPUs can be obtained with len(psutil.Process().cpu_affinity()).
If logical is False return the number of physical cores only

Memory

psutil.virtual_memory():獲取內存的使用信息。
psutil.swap_memory():獲取交換內存的使用信息。

Disk

psutil.disk_partitions(all=False):獲取硬盤分區信息。
psutil.disk_usage(path):獲取硬盤使用信息。
psutil.disk_io_counters(perdisk=False, nowrap=True):獲取磁盤IO信息。

Network

psutil.net_io_counters(pernic=False):獲取網絡IO信息。
psutil.net_connections(kind='inet'):獲取socket連接信息。
psutil.net_if_addrs():獲取各網卡的各種地址信息(包括IP地址、網絡地址、廣播地址等)。
psutil.net_if_stats():獲取網卡的硬件信息(包括是否啟用、單工還是雙工、speed、MTU)。

Sensor

psutil.sensors_temperatures(fahrenheit=False):獲取硬件的溫度(包括CPU、硬盤等)。
psutil.sensors_fans():獲取風扇的轉速。
psutil.sensors_battery():獲取電池狀態信息。

其它系統信息

psutil.boot_time():獲取系統的啟動時間,注意不是啟動時長,是啟動時的時間戳。
psutil.users():獲取當前登錄系統的用戶。

Process,獲取進程信息

psutil.pids():獲取系統當前正在運行的所有PID。返回的是一個進程號列表。
psutil.pid_exists(pid):檢測指定的pid是否存在。
psutil.wait_procs(procs, timeout=None, callback=None):等待進程結束。

psutil.process_iter(attrs=None, ad_value=None):返回一個生成器,迭代獲取所有進程的屬性信息,可以用attrs指定要顯示的屬性,然後調用Process.as_dict()方法即可獲取相關屬性。

>>> psutil.process_iter()
<generator object process_iter at 0x7f5321d8e468>
>>> p = psutil.process_iter()
>>> for i in p:
... print(i)
...
psutil.Process(pid=1, name='systemd')
psutil.Process(pid=2, name='kthreadd')
psutil.Process(pid=3, name='ksoftirqd/0')
psutil.Process(pid=5, name='kworker/0:0H')
... ...
psutil.Process(pid=32284, name='bioset')
psutil.Process(pid=32285, name='dm-thin')
psutil.Process(pid=32286, name='bioset')

Process class

class psutil.Process(pid=None):Process類。
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.
pid:The process PID. This is the only (read-only) attribute of the class.
ppid():The process parent PID.
name():The process name.
exe():The process executable as an absolute path.
cmdline():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.
environ():The environment variables of the process as a dict. Note: this might not reflect changes made after the process started.
create_time():The process creation time as a floating point number expressed in seconds since the epoch, in UTC. The return value is cached after first call.
parent():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.
status():The current process status as a string.
cwd():The process current working directory as an absolute path.
username():The name of the user that owns the process. On UNIX this is calculated by using real process uid.
uids():The real, effective and saved user ids of this process as a named tuple.
gids():The real, effective and saved group ids of this process as a named tuple.
terminal():The terminal associated with this process, if any, else None.
io_counters():Return process I/O statistics as a named tuple.
num_fds():The number of file descriptors currently opened by this process (non cumulative).
num_handles():The number of handles currently used by this process (non cumulative).
num_threads():The number of threads currently used by this process (non cumulative).
threads():Return threads opened by process as a list of named tuples including thread id and thread CPU times (user/system).
cpu_times():Return a (user, system, children_user, children_system) named tuple representing the accumulated process time, in seconds.
cpu_percent(interval=None):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.
cpu_affinity(cpus=None):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. 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).
cpu_num():Return what CPU this process is currently running on.
memory_info():Return a named tuple with variable fields depending on the platform representing memory information about the process.
memory_percent(memtype="rss"):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").
children(recursive=False):Return the children of this process as a list of Process objects, preemptively checking whether PID has been reused. If recursive is True return all the parent descendants.
open_files():Return regular files opened by process as a list of named tuples.
connections(kind="inet"):Return socket connections opened by process as a list of named tuples.
is_running():Return whether the current process is running in the current process list.
send_signal(signal):Send a signal to process preemptively checking whether PID has been reused.
suspend():Suspend process execution with SIGSTOP signal preemptively checking whether PID has been reused.
resume():Resume process execution with SIGCONT signal preemptively checking whether PID has been reused.
terminate():Terminate the process with SIGTERM signal preemptively checking whether PID has been reused.
kill():Kill the current process by using SIGKILL signal preemptively checking whether PID has been reused.
wait(timeout=None):Wait for process termination and if the process is a children of the current one also return the exit code, else None. To wait for multiple processes use psutil.wait_procs().

Popen class

class psutil.Popen(*args, **kwargs):Popen類。

A more convenient interface to stdlib subprocess.Popen. It starts a sub process and you deal with it exactly as when using subprocess.Popen but in addition it also provides all the methods of psutil.Process class.

是一個比subprocess.Popen標准庫更方便的接口。它啟動一個子進程,使用方法與 subprocess.Popen 完全相同,不過它提供所有 psutil.Process 的類,所以它的使用方法除了上面列出的方法,還需要參考 subprocess.Popen 支持的方法。不同的是,它會事先檢查PID是否被復用,不會意外殺掉其它進程。

>>> import psutil
>>> from subprocess import PIPE
>>> p = psutil.Popen(["/usr/bin/python", "-c", "print('hello')"], stdout=PIPE)
>>>
>>> p.name()
'python'
>>> p.username()
'root'
>>> p.communicate()
(b'hello\n', None)
>>> p.wait()
0

需要總結一下的是,subprocess和psutil.Popen常用來調用外部命令,也就是執行系統命令,進程間只能通過管道進行文本交流,從上面例子中的 PIPE 可見一斑,這裡可以閱讀一下subprocess的官方文檔便知。

另外,常用來調用系統命令的接口還有 os.system()和os.popen(),不過設計和使用上更簡單一些。


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved