Python的psutil模塊詳解
一、psutil模塊:
1.psutil介紹
psutil是一個(gè)跨平臺(tái)庫(kù)(//pythonhosted.org/psutil/)能夠輕松實(shí)現(xiàn)獲取系統(tǒng)運(yùn)行的進(jìn)程和系統(tǒng)利用率(包括CPU、內(nèi)存、磁盤(pán)、網(wǎng)絡(luò)等)信息。它主要用來(lái)做系統(tǒng)監(jiān)控,性能分析,進(jìn)程管理。它實(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).
2.安裝psutil模塊:
CentOS安裝psutil包:
python版本:3.5
wget https://pypi.python.org/packages/source/p/psutil/psutil-3.2.1.tar.gz --no-check-certificate
tar zxvf psutil-3.2.1.tar.gz
cd psutil-3.2.1
python setup.py install
Windos安裝psutil包:
D:\python35\Scripts>pip3.exe install psutil
Collecting psutil
Downloading psutil-5.3.1-cp35-cp35m-win_amd64.whl (215kB)
100% |████████████████████████████████| 225kB 84kB/s
Installing collected packages: psutil
Successfully installed psutil-5.3.1二、.獲取系統(tǒng)基本信息的使用:
1.CPU信息
使用cpu_times方法獲取cpu的完整信息,如下所示。
>>> psutil.cpu_times() scputimes(user=650613.02, nice=22.14, system=154916.5, idle=16702285.26, iowait=68894.55, irq=3.38, softirq=7075.65, steal=0.0, guest=0.0) >>>
獲取單個(gè)數(shù)據(jù),如用戶(hù)的cpu時(shí)或io等待時(shí)間,如下所示:
>>> psutil.cpu_times().user 650617.11 >>> psutil.cpu_times().iowait 68894.63 >>>
獲取cpu邏輯和物理個(gè)數(shù),默認(rèn)logical值為T(mén)rue 。
#CPU邏輯個(gè)數(shù) >>> psutil.cpu_count() 2 #CPU物理個(gè)數(shù) >>> psutil.cpu_count(logical=False) 1 >>>
獲取cpu的使用率:
>>> psutil.cpu_percent() 2.5 >>> psutil.cpu_percent(1) 2.5 >>>
2.內(nèi)存信息
內(nèi)存信息的獲取主要使用virtual_memory方法。swap使用就用swap_memory方法。
>>> mem = psutil.virtual_memory() >>> mem svmem(total=4018601984, available=1066205184, percent=73.5, used=3904004096, free=114597888, active=3302174720, inactive=426078208, buffers=156520448, cached=795086848) >>> mem.total 4018601984 >>> mem.used 3904004096 >>> mem.free 114597888 >>> print(mem.total/1024/1024) 3832.4375 >>>
其中percent表示實(shí)際已經(jīng)使用的內(nèi)存占比,即(1047543808-717537280)/1047543808*100% 。available表示還可以使用的內(nèi)存。
3.磁盤(pán)信息
磁盤(pán)信息主要有兩部分,一個(gè)是磁盤(pán)的利用率,一個(gè)是io,他們分別可以通過(guò)disk_usage和disk_io_counters方法獲取。
如下先獲取分區(qū)信息,然后看下根分區(qū)的使用情況:
>>> psutil.disk_partitions()
[sdiskpart(device='/dev/mapper/root', mountpoint='/', fstype='ext4', opts='rw,errors=remount-ro'), sdiskpart(device='/dev/sda1', mountpoint='/boot', fstype='ext2', opts='rw')]
>>> psutil.disk_usage('/')
sdiskusage(total=42273669120, used=17241096192, free=22885195776, percent=40.8)
>>> 默認(rèn)disk_io_counters方法獲取的是硬盤(pán)總的io數(shù)和讀寫(xiě)信息,如果需要獲取單個(gè)分區(qū)的io和讀寫(xiě)信息加上"perdisk=True"參數(shù)。
>>> psutil.disk_io_counters()
sdiskio(read_count=638190, write_count=77080153, read_bytes=16037795840, write_bytes=1628871606272, read_time=2307367, write_time=1777841305)
>>> psutil.disk_io_counters(perdisk=True)
{'vdb1': sdiskio(read_count=312, write_count=0, read_bytes=1238016, write_bytes=0, read_time=95, write_time=0), 'vda1': sdiskio(read_count=637878, write_count=77080257, read_bytes=16036557824, write_bytes=1628873314304, read_time=2307272, write_time=1777841879)}
>>> 4.網(wǎng)絡(luò)信息:
網(wǎng)絡(luò)io和磁盤(pán)io使用方法差不多,主要使用net_io_counters方法,如果需要獲取單個(gè)網(wǎng)卡的io信息,加上pernic=True參數(shù)。
#獲取網(wǎng)絡(luò)總的io情況
>>>
>>> psutil.net_io_counters()
snetio(bytes_sent=525490132009, bytes_recv=409145642892, packets_sent=948527563, packets_recv=778182181, errin=0, errout=0, dropin=0, dropout=0)
#獲取網(wǎng)卡的io情況
>>>
>>> psutil.net_io_counters(pernic=True)
{'lo': snetio(bytes_sent=56524704027, bytes_recv=56524704027, packets_sent=33602236, packets_recv=33602236, errin=0, errout=0, dropin=0, dropout=0), 'eth0': snetio(bytes_sent=468966480940, bytes_recv=352622081327, packets_sent=914930488, packets_recv=744583332, errin=0, errout=0, dropin=0, dropout=0)}
>>> 5.其他系統(tǒng)信息:
1.獲取開(kāi)機(jī)時(shí)間
##以linux時(shí)間格式返回,可以使用時(shí)間戳轉(zhuǎn)換
>>> psutil.boot_time()
1496647567.0
#轉(zhuǎn)換成自然時(shí)間格式
>>> psutil.boot_time()
1496647567.0
>>> datetime.datetime.fromtimestamp(psutil.boot_time ()).strftime("%Y-%m-%d %H: %M: %S")
'2017-06-05 15: 26: 07'
>>> 2.查看系統(tǒng)全部進(jìn)程
>>> psutil.pids() [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 46, 47, 48, 49, 50, 51, 52, 53, 60, 61, 63, 64, 65, 97, 98, 279, 280, 331, 398, 481, 676, 693, 769, 845, 848, 1023, 1085, 1108, 1355, 1366, 1457, 1474, 1475, 1494, 1541, 1543, 1545, 1546, 1548, 1550, 1552, 2829, 12436, 12913, 13129, 16022, 16029, 16030, 16031, 16032, 16033, 16518, 16520, 17088, 17124, 19203, 25382, 32679]
3.查看單個(gè)進(jìn)程
p = psutil.Process(16031)
p.name() #進(jìn)程名
p.exe() #進(jìn)程的bin路徑
p.cwd() #進(jìn)程的工作目錄絕對(duì)路徑
p.status() #進(jìn)程狀態(tài)
p.create_time() #進(jìn)程創(chuàng)建時(shí)間
p.uids() #進(jìn)程uid信息
p.gids() #進(jìn)程的gid信息
p.cpu_times() #進(jìn)程的cpu時(shí)間信息,包括user,system兩個(gè)cpu信息
p.cpu_affinity() #get進(jìn)程cpu親和度,如果要設(shè)置cpu親和度,將cpu號(hào)作為參考就好
p.memory_percent() #進(jìn)程內(nèi)存利用率
p.memory_info() #進(jìn)程內(nèi)存rss,vms信息
p.io_counters() #進(jìn)程的IO信息,包括讀寫(xiě)IO數(shù)字及參數(shù)
p.connectios() #返回進(jìn)程列表
p.num_threads() #進(jìn)程開(kāi)啟的線程數(shù)
聽(tīng)過(guò)psutil的Popen方法啟動(dòng)應(yīng)用程序,可以跟蹤程序的相關(guān)信息
from subprocess import PIPE
p = psutil.Popen(["/usr/bin/python", "-c", "print('hello')"],stdout=PIPE)
p.name()
p.username()查看系統(tǒng)硬件腳本:
硬件信息腳本
1 #!/usr/bin/env python
2 #coding:utf-8
3
4 import psutil
5 import datetime
6 import time
7
8 # 當(dāng)前時(shí)間
9 now_time = time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime(time.time()))
10 print(now_time)
11
12 # 查看cpu物理個(gè)數(shù)的信息
13 print(u"物理CPU個(gè)數(shù): %s" % psutil.cpu_count(logical=False))
14
15 #CPU的使用率
16 cpu = (str(psutil.cpu_percent(1))) + '%'
17 print(u"cup使用率: %s" % cpu)
18
19 #查看內(nèi)存信息,剩余內(nèi)存.free 總共.total
20 #round()函數(shù)方法為返回浮點(diǎn)數(shù)x的四舍五入值。
21
22 free = str(round(psutil.virtual_memory().free / (1024.0 * 1024.0 * 1024.0), 2))
23 total = str(round(psutil.virtual_memory().total / (1024.0 * 1024.0 * 1024.0), 2))
24 memory = int(psutil.virtual_memory().total - psutil.virtual_memory().free) / float(psutil.virtual_memory().total)
25 print(u"物理內(nèi)存: %s G" % total)
26 print(u"剩余物理內(nèi)存: %s G" % free)
27 print(u"物理內(nèi)存使用率: %s %%" % int(memory * 100))
28 # 系統(tǒng)啟動(dòng)時(shí)間
29 print(u"系統(tǒng)啟動(dòng)時(shí)間: %s" % datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S"))
30
31 # 系統(tǒng)用戶(hù)
32 users_count = len(psutil.users())
33 #
34 # >>> for u in psutil.users():
35 # ... print(u)
36 # ...
37 # suser(name='root', terminal='pts/0', host='61.135.18.162', started=1505483904.0)
38 # suser(name='root', terminal='pts/5', host='61.135.18.162', started=1505469056.0)
39 # >>> u.name
40 # 'root'
41 # >>> u.terminal
42 # 'pts/5'
43 # >>> u.host
44 # '61.135.18.162'
45 # >>> u.started
46 # 1505469056.0
47 # >>>
48
49 users_list = ",".join([u.name for u in psutil.users()])
50 print(u"當(dāng)前有%s個(gè)用戶(hù),分別是 %s" % (users_count, users_list))
51
52 #網(wǎng)卡,可以得到網(wǎng)卡屬性,連接數(shù),當(dāng)前流量等信息
53 net = psutil.net_io_counters()
54 bytes_sent = '{0:.2f} Mb'.format(net.bytes_recv / 1024 / 1024)
55 bytes_rcvd = '{0:.2f} Mb'.format(net.bytes_sent / 1024 / 1024)
56 print(u"網(wǎng)卡接收流量 %s 網(wǎng)卡發(fā)送流量 %s" % (bytes_rcvd, bytes_sent))
57
58 io = psutil.disk_partitions()
59 # print(io)
60 # print("io[-1]為",io[-1])
61 #del io[-1]
62
63 print('-----------------------------磁盤(pán)信息---------------------------------------')
64
65 print("系統(tǒng)磁盤(pán)信息:" + str(io))
66
67 for i in io:
68 o = psutil.disk_usage(i.device)
69 print("總?cè)萘浚? + str(int(o.total / (1024.0 * 1024.0 * 1024.0))) + "G")
70 print("已用容量:" + str(int(o.used / (1024.0 * 1024.0 * 1024.0))) + "G")
71 print("可用容量:" + str(int(o.free / (1024.0 * 1024.0 * 1024.0))) + "G")
72
73 print('-----------------------------進(jìn)程信息-------------------------------------')
74 # 查看系統(tǒng)全部進(jìn)程
75 for pnum in psutil.pids():
76 p = psutil.Process(pnum)
77 print(u"進(jìn)程名 %-20s 內(nèi)存利用率 %-18s 進(jìn)程狀態(tài) %-10s 創(chuàng)建時(shí)間 %-10s " \
78 % (p.name(), p.memory_percent(), p.status(), p.create_time()))到此這篇關(guān)于Python的psutil模塊詳解的文章就介紹到這了,更多相關(guān)psutil模塊詳解內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python 人工智能老照片修復(fù)算法學(xué)習(xí)
老舊或者破損的照片如何修復(fù)呢?本文主要介紹了一個(gè)非常不錯(cuò)的照片恢復(fù)開(kāi)源項(xiàng)目:Bringing-Old-Photos-Back-to-Life。感興趣的小伙伴快來(lái)看看呀2021-11-11
pytorch實(shí)現(xiàn)mnist數(shù)據(jù)集的圖像可視化及保存
今天小編就為大家分享一篇pytorch實(shí)現(xiàn)mnist數(shù)據(jù)集的圖像可視化及保存,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-01-01
教你從零開(kāi)始實(shí)現(xiàn)貪吃蛇Python小游戲
這篇文章主要教你從零開(kāi)始實(shí)現(xiàn)貪吃蛇Python小游戲,沒(méi)有使用pygame庫(kù),附帶源碼和注釋,非常有意思,需要的朋友可以參考下2023-03-03
python使用梯度下降算法實(shí)現(xiàn)一個(gè)多線性回歸
這篇文章主要為大家詳細(xì)介紹了python使用梯度下降算法實(shí)現(xiàn)一個(gè)多線性回歸,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-03-03
python小白練習(xí)題之條件控制與循環(huán)控制
Python 中的條件控制和循環(huán)語(yǔ)句都非常簡(jiǎn)單,也非常容易理解,與其他編程語(yǔ)言類(lèi)似,下面這篇文章主要給大家介紹了關(guān)于python小白練習(xí)題之條件控制與循環(huán)控制的相關(guān)資料,需要的朋友可以參考下2021-10-10
使用Python通過(guò)win32 COM實(shí)現(xiàn)Word文檔的寫(xiě)入與保存方法
今天小編就為大家分享一篇使用Python通過(guò)win32 COM實(shí)現(xiàn)Word文檔的寫(xiě)入與保存方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-05-05
深入學(xué)習(xí)Python+Opencv常用四種圖像處理操作
本文主要介紹了深入學(xué)習(xí)Pytho+OpenCV實(shí)現(xiàn)的基本圖像處理操作,例如:改變圖像大小,圖片色彩轉(zhuǎn)換,圖片模糊等,代碼具有一定的學(xué)習(xí)價(jià)值,感興趣的小伙伴可以關(guān)注一下2021-11-11
Django之編輯時(shí)根據(jù)條件跳轉(zhuǎn)回原頁(yè)面的方法
今天小編就為大家分享一篇Django之編輯時(shí)根據(jù)條件跳轉(zhuǎn)回原頁(yè)面的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-08-08
淺析python 中__name__ = ''__main__'' 的作用
這篇文章主要介紹了python 中__name__ = '__main__' 的作用,對(duì)于初學(xué)者來(lái)說(shuō)很有幫助,需要的朋友可以參考下2014-07-07

