哈哈~
一、簡(jiǎn)介
psutil
是一個(gè)跨平臺(tái)庫(kù)
能夠輕松實(shí)現(xiàn)獲取系統(tǒng)運(yùn)行的進(jìn)程和系統(tǒng)利用率
包括 CPU、內(nèi)存、磁盤(pán)、網(wǎng)絡(luò)等信息
psutil
主要應(yīng)用于系統(tǒng)監(jiān)控、分析和限制系統(tǒng)資源及進(jìn)程的管理
psutil
實(shí)現(xiàn)了同等命令行工具提供的功能,如 ps、top、lsof、netstat、ifconfig、who、df、kill、free、nice、ionice、iostat、iotop、uptime、pidof、tty、taskset、pmap 等。目前支持 32 位和 64 位的 Linux、Windows、OS X、FreeBSD 和 Sun Solaris 等操作系統(tǒng)
安裝方法:
sudo pip3 install psutil
二、基本用法
獲取 CPU 信息:
In [3]: import psutil
In [4]: psutil.cpu_count() # 邏輯 cpu 的個(gè)數(shù)
Out[4]: 2
In [5]: psutil.cpu_count(logical=False) # 物理 cpu 的個(gè)數(shù)
Out[5]: 2
獲取內(nèi)存信息:
In [6]: mem = psutil.virtual_memory()
In [7]: mem # 全部信息
Out[7]: svmem(total=4112044032, available=1084837888,
percent=73.6, used=2760781824, free=700198912,
active=1513553920, inactive=797716480, buffers=71434240,
cached=579629056, shared=33579008, slab=121634816)
In [8]: mem.total # 總內(nèi)存
Out[8]: 4112044032
In [9]: mem.available # 可用內(nèi)存
Out[9]: 1084837888
In [10]: mem.used # 已用內(nèi)存
Out[10]: 2760781824
獲取 swap 內(nèi)存信息:
In [11]: psutil.swap_memory()
Out[11]: sswap(total=4291817472, used=507510784,
free=3784306688, percent=11.8, sin=22065152, sout=518934528)
獲取進(jìn)程信息:
In [18]: psutil.pids() # 全部 PID
Out[18]:
[1,
2,
4,
6,
... ...
19383,
19402,
19542]
In [19]: p = psutil.Process(19542) # 某個(gè)進(jìn)程的信息
In [20]: p
Out[20]: psutil.Process(pid=19542, name='kworker/u256:2', started='16:44:28')
In [21]: p.status
Out[21]: <bound method Process.status of
psutil.Process(pid=19542, name='kworker/u256:2', started='16:44:28')>
In [22]: p.status()
Out[22]: 'idle'
獲取當(dāng)前網(wǎng)絡(luò)連接信息:
# 需要用 sudo 運(yùn)行,否則會(huì)報(bào)錯(cuò):AccessDenied
# 因?yàn)?psutil 獲取信息也要通過(guò)系統(tǒng)接口,而獲取網(wǎng)絡(luò)連接需要 root 權(quán)限
~ sudo ipython
Password:
Python 3.7.0 (default, Jul 23 2018, 20:22:55)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.5.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: import psutil
In [2]: psutil.net_connections() # 獲取網(wǎng)絡(luò)連接信息
Out[2]:
[sconn(fd=4, family=<AddressFamily.AF_INET: 2>, type=2,
laddr=addr(ip='0.0.0.0', port=0), raddr=(), status='NONE', pid=4627),
sconn(fd=8, family=<AddressFamily.AF_INET: 2>, type=2,
laddr=addr(ip='0.0.0.0', port=0), raddr=(), status='NONE', pid=4627),
... ...
類(lèi)似 Linux 的 ps
命令:
In [8]: psutil.test()
USER PID %MEM VSZ RSS TTY START TIME COMMAND
root 0 25.5 74629472 2139112 ? Aug31 33:05 kernel_task
root 1 0.1 4328532 9236 ? Aug31 01:32 launchd
root 39 ? 4306056 1152 ? Aug31 00:03 syslogd
root 40 0.2 4337260 15900 ? Aug31 00:09 UserEventAgent