新聞中心
psutil (python system and process utilities) 是一個(gè)跨平臺(tái)的第三方庫,能夠輕松實(shí)現(xiàn)獲取系統(tǒng)運(yùn)行的進(jìn)程和系統(tǒng)利用率(包擴(kuò)CPU、內(nèi)存、磁盤、網(wǎng)絡(luò)等)信息。它主要用于系統(tǒng)監(jiān)控、分析、限制系統(tǒng)資源和進(jìn)程的管理。

image-20220312225149930
安裝
pip install psutil
獲取CPU信息
統(tǒng)計(jì)cpu開銷時(shí)間
psutil.cpu_times()
返回系統(tǒng)CPU時(shí)間
-
user:在用戶模式下執(zhí)行普通進(jìn)程所花費(fèi)的時(shí)間
-
system: 在內(nèi)核模式下執(zhí)行的進(jìn)程所花費(fèi)的時(shí)間
-
idle:空閑時(shí)間
-
nice :在用戶模式下執(zhí)行完好的(優(yōu)先級(jí))進(jìn)程所花費(fèi)的時(shí)間; 在Linux上,這還包括
guest_nice時(shí)間
-
iowait : 等待I / O完成所花費(fèi)的時(shí)間。
-
irq :服務(wù)硬件中斷所花費(fèi)的時(shí)間
-
softirq : 服務(wù)軟件中斷所花費(fèi)的時(shí)間
-
steal : 在虛擬環(huán)境中運(yùn)行的其他操作系統(tǒng)所花費(fèi)的時(shí)間
-
guest :在Linux內(nèi)核控制下為來guest系統(tǒng)運(yùn)行虛擬CPU所花費(fèi)的時(shí)間
-
guest_nice:運(yùn)行良好的guest所花費(fèi)的時(shí)間
如需顯示所有CPU核心信息,應(yīng)顯示的指出psutil.cpu_times(percpu=Ture),返回一個(gè)列表, 列表的第一個(gè)元素是指第一個(gè)CPU,第二個(gè)元素是指第二個(gè)CPU,依此類推,一般情況下只關(guān)注user,system,以及idle,這三個(gè)參數(shù),表示CPU的用戶/系統(tǒng)/空閑時(shí)間。
# Centos7.8
>>> import psutil
>>> psutil.cpu_times()
scputimes(user=56276.04, nice=6.9, system=46298.69, idle=7267935.28, iowait=1748.04, irq=0.0, softirq=288.37, steal=0.0, guest=0.0, guest_nice=0.0)
# windows 10
>>> psutil.cpu_times(percpu=True)
[scputimes(user=120708.328125, system=113197.0625, idle=926771.3593749999, interrupt=6374.4375, dpc=3362.828125),
scputimes(user=104530.18749999999, system=87954.64062500012, idle=968191.6406249999, interrupt=1626.5625, dpc=281.8125),
scputimes(user=127384.45312499999, system=110084.546875, idle=923207.453125, interrupt=1679.453125, dpc=336.640625),
scputimes(user=110810.578125, system=82547.015625, idle=967318.875, interrupt=1359.25, dpc=262.21875)]
統(tǒng)計(jì)CPU利用率
psutil.cpu_percent(interval=None,percpu=False)
當(dāng)interval> 0.0時(shí),將比較該間隔前后的系統(tǒng)CPU時(shí)間(阻塞)。 當(dāng)interval為0.0或無時(shí),比較自上次調(diào)用或模塊導(dǎo)入以來經(jīng)過的系統(tǒng)CPU時(shí)間,立即返回。 這意味著第一次調(diào)用它會(huì)返回一個(gè)無意義的0.0值,應(yīng)該忽略它。 在這種情況下,為確保準(zhǔn)確性,建議在兩次調(diào)用之間至少調(diào)用0.1秒。
# 每隔兩秒刷新CPU使用率,累計(jì)8次
>>> for x in range(8):
... print(psutil.cpu_percent(interval=2, percpu=True))
[30.5, 17.8, 30.2, 24.6]
[16.3, 20.2, 14.0, 14.0]
[12.1, 3.9, 4.7, 3.9]
[26.4, 16.3, 18.6, 16.3]
[13.1, 9.3, 7.8, 10.1]
[33.6, 40.3, 48.4, 34.4]
[17.6, 8.5, 14.7, 7.8]
[23.1, 7.8, 21.5, 8.5]
統(tǒng)計(jì)CPU核心數(shù)
# 默認(rèn)統(tǒng)計(jì)CPU邏輯核心數(shù)
>>> psutil.cpu_count() # CPU邏輯核心數(shù)
4
>>> psutil.cpu_count(logical=False) # cpu物理核心數(shù)
2
CPU頻率
# 顯示當(dāng)前cpu的主頻率
>>> psutil.cpu_freq()
scpufreq(current=1876.0, min=0.0, max=1896.0)
負(fù)載
# 以元組的形式返回最近1、5和15分鐘內(nèi)的平均系統(tǒng)負(fù)載。 在Windows上,這是通過使用Windows API模擬的,該API產(chǎn)生一個(gè)線程,該線程保持在后臺(tái)運(yùn)行,并每5秒更新一次結(jié)果,從而模仿UNIX行為。 因此,在Windows上,第一次調(diào)用此方法,在接下來的5秒鐘內(nèi),它將返回?zé)o意義的(0.0,0.0,0.0)元組。
>>> psutil.getloadavg()
(0.0, 0.01, 0.05)
獲取內(nèi)存信息
# windows 10 返回內(nèi)存使用情況
>>> memory = psutil.virtual_memory()
>>> memory
svmem(total=8463876096, available=2596061184, percent=69.3, used=5867814912, free=2596061184)
>>> memory.total
8463876096
# centos7.8
>>> psutil.virtual_memory()
svmem(total=1927192576, available=1060913152, percent=45.0, used=693989376, free=103620608, active=1383866368, inactive=288067584, buffers=143511552, cached=986071040, shared=589824, slab=93745152)
返回的是單位是字節(jié)Byte
重點(diǎn)關(guān)注的參數(shù):
-
total=8463876096 總共8.46GB
-
available=2596061184 可用2.59GB
-
percent=69.3 使用率69.3%
-
used=5867814912 已使用5.86GB
獲取swap 內(nèi)存信息
# windows 10
>>> psutil.swap_memory()
sswap(total=13326721024, used=9382895616, free=3943825408, percent=70.4, sin=0, sout=0)
獲取磁盤信息
獲取磁盤分區(qū)信息
In [35]: psutil.disk_partitions()
Out[35]: [sdiskpart(device='/dev/vda1', mountpoint='/', fstype='ext4', opts='rw,relatime,data=ordered')]
獲取指定分區(qū)的使用情況
# centos 7.8
In [36]: psutil.disk_usage('/')
Out[36]: sdiskusage(total=42140479488, used=12435881984, free=27755200512, percent=30.9)
# windows 10
In [32]: psutil.disk_usage('C:\\')
Out[32]: sdiskusage(total=125917933568, used=89807781888, free=36110151680, percent=71.3)
獲取硬盤的IO個(gè)數(shù),讀寫信息
# windows 10
In [37]: psutil.disk_io_counters()
Out[37]: sdiskio(read_count=7703266, write_count=11199399, read_bytes=209586859008, write_bytes=217863440384, read_time=46821, write_time=5137)
# 獲取單個(gè)分區(qū)的 io個(gè)數(shù),讀寫信息
In [38]: psutil.disk_io_counters(perdisk=True)
Out[38]:
{'PhysicalDrive0': sdiskio(read_count=980771, write_count=399173, read_bytes=39607087616, write_bytes=8268857344, read_time=38514, write_time=1396),
'PhysicalDrive1': sdiskio(read_count=6723984, write_count=10805960, read_bytes=169995229696, write_bytes=209674449408, read_time=8309, write_time=3743)}
獲取網(wǎng)絡(luò)信息
獲取網(wǎng)絡(luò)讀寫字節(jié)/包的個(gè)數(shù)
# windows 10
In [39]: psutil.net_io_counters()
Out[39]: snetio(bytes_sent=45955043, bytes_recv=736052740, packets_sent=383832, packets_recv=589165, errin=0, errout=0, dropin=0, dropout=0)
# windows 10 輸出每個(gè)網(wǎng)絡(luò)接口的IO信息
In [40]: psutil.net_io_counters(pernic=True)
Out[40]:
{'Ethernet': snetio(bytes_sent=0, bytes_recv=0, packets_sent=0, packets_recv=0, errin=0, errout=0, dropin=0, dropout=0),
'Local Area Connection* 11': snetio(bytes_sent=0, bytes_recv=0, packets_sent=0, packets_recv=0, errin=0, errout=0, dropin=0, dropout=0),
......}
獲取系統(tǒng)范圍的套接字連接
# inet 代表 IPv4 and IPv6
In [42]: psutil.net_connections(kind='inet')
Out[42]:
[pconn(fd=115, family=
,
type=
, laddr=addr(ip=
'10.0.0.1', port=48776), raddr=addr(ip=
'93.186.135.91', port=80), status=
'ESTABLISHED', pid=1254), pconn(fd=117, family=
,
type=
, laddr=addr(ip=
'10.0.0.1', port=43761), raddr=addr(ip=
'72.14.234.100', port=80), status=
'CLOSING', pid=2987), pconn(fd=-1, family=
,
type=
, laddr=addr(ip=
'10.0.0.1', port=60759), raddr=addr(ip=
'72.14.234.104', port=80), status=
'ESTABLISHED', pid=None), pconn(fd=-1, family=
,
type=
, laddr=addr(ip=
'10.0.0.1', port=51314), raddr=addr(ip=
'72.14.234.83', port=443), status=
'SYN_SENT', pid=None) ...]
獲取網(wǎng)絡(luò)接口信息
>>> psutil.net_if_addrs()
{'lo': [snicaddr(family=
, address=
'127.0.0.1', netmask=
'255.0.0.0', broadcast=
'127.0.0.1', ptp=None), snicaddr(family=
, address=
'::1', netmask=
'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None, ptp=None), snicaddr(family=
, address=
'00:00:00:00:00:00', netmask=None, broadcast=
'00:00:00:00:00:00', ptp=None)],
'wlan0': [snicaddr(family=
, address=
'192.168.1.3', netmask=
'255.255.255.0', broadcast=
'192.168.1.255', ptp=None), snicaddr(family=
, address=
'fe80::c685:8ff:fe45:641%wlan0', netmask=
'ffff:ffff:ffff:ffff::', broadcast=None, ptp=None), snicaddr(family=
, address=
'c4:85:08:45:06:41', netmask=None, broadcast=
'ff:ff:ff:ff:ff:ff', ptp=None)]} >>>
獲取網(wǎng)絡(luò)接口狀態(tài)
>>> psutil.net_if_stats()
{'eth0': snicstats(isup=True, duplex=
, speed=100, mtu=1500),
'lo': snicstats(isup=True, duplex=
, speed=0, mtu=65536)}
獲取用戶信息
>>> psutil.users()
[suser(name='giampaolo', terminal='pts/2', host='localhost', started=1340737536.0, pid=1352),
suser(name='giampaolo', terminal='pts/3', host='localhost', started=1340737792.0, pid=1788)]
獲取開機(jī)時(shí)間
In [49]: import datetime
# 獲取系統(tǒng)開機(jī)時(shí)間,以Linux時(shí)間戳格式返回
In [50]: psutil.boot_time()
Out[50]: 1595251273.0
# 轉(zhuǎn)換為人可讀的方式
In [51]: datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
Out[51]: '2020-07-20 21:21:13'
獲取進(jìn)程信息
獲取所有進(jìn)程信息
# 獲取所有進(jìn)程pid
In [52]: psutil.pids()
Out[52]:
[1,
2,
4,
...]
# 實(shí)例化一個(gè)Process對(duì)象,參數(shù)為進(jìn)程PID
In [2]: p = psutil.Process(4313)
In [3]: p
Out[3]: psutil.Process(pid=4313, name='ipython', status='running', started='21:23:58')
# 進(jìn)程bin路徑
In [4]: p.exe()
Out[4]: '/usr/bin/python3.6'
# 進(jìn)程工作目錄絕對(duì)路徑
In [5]: p.cwd()
Out[5]: '/root'
# 進(jìn)程號(hào)
In [7]: p.pid
Out[7]: 4313
# 父進(jìn)程號(hào)
In [8]: p.ppid()
Out[8]: 4139
# 進(jìn)程狀態(tài)
In [11]: p.status()
Out[11]: 'running'
# 進(jìn)程 rss,vms信息
In [19]: p.memory_info()
Out[19]: pmem(rss=44388352, vms=347344896, shared=5902336, text=4096, lib=0, data=113049600, dirty=0)
# 進(jìn)程內(nèi)存利用率
In [20]: p.memory_percent()
Out[20]: 2.303264995557974
| Linux | Windows | macOS |
|---|---|---|
cpu_num() |
cpu_percent() |
cpu_percent() |
cpu_percent() |
cpu_times() |
cpu_times() |
cpu_times() |
io_counters() |
memory_info() |
create_time() |
memory_info() |
memory_percent() |
name() |
memory_maps() |
num_ctx_switches() |
ppid() |
num_ctx_switches() |
num_threads() |
status() |
num_handles() |
|
terminal() |
num_threads() |
create_time() |
username() |
gids() |
|
gids() |
name() |
|
num_ctx_switches() |
exe() |
ppid() |
num_threads() |
name() |
status() |
uids() |
terminal() |
|
username() |
uids() |
|
username() |
||
memory_full_info() |
||
memory_maps() |
||
| speedup: +2.6x | speedup: +1.8x / +6.5x | speedup: +1.9x |
本文標(biāo)題:Python中psutil庫的使用方法
網(wǎng)頁地址:http://m.fisionsoft.com.cn/article/cddddii.html


咨詢
建站咨詢
