python中系統資訊獲取psutil使用

2021-07-02 17:02:43 字數 2343 閱讀 4115

#!/usr/bin/env python

#coding:utf-8

import psutil

import time

import sys

from optparse import optionparser

parser = optionparser()

parser.add_option("-t", "--time", dest="time",

parser.add_option("-d", "--deamon",action="store_false", dest="deamon", default=true,

help="後台執行此指令碼")

def sysinfo():

boot_start = time.strftime("%y-%m-%d %h:%m:%s",time.localtime(psutil.boot_time()))

time.sleep(0.5)

cpu_usage = psutil.cpu_percent()

ram = int(psutil.virtual_memory().total/(1027*1024))

ram_percent = psutil.virtual_memory().percent

swap = int(psutil.swap_memory().total/(1027*1024))

swap_percent = psutil.swap_memory().percent

net_sent = psutil.net_io_counters().bytes_sent

net_recv = psutil.net_io_counters().bytes_recv

net_spkg = psutil.net_io_counters().packets_sent

net_rpkg = psutil.net_io_counters().packets_recv

bfh = r'%'

print " \033[1;32m當前cpu使用率:%s%s\033[1;m" % (cpu_usage,bfh)

print " \033[1;32m物理記憶體:%dm\t使用率:%s%s\033[1;m" % (ram,ram_percent,bfh)

print "\033[1;32mswap記憶體:%dm\t使用率:%s%s\033[1;m" % (swap,swap_percent,bfh)

print " \033[1;32m傳送:%d byte\t傳送包數:%d個\033[1;m" % (net_sent,net_spkg)

print " \033[1;32m接收:%d byte\t接收包數:%d個\033[1;m" % (net_recv,net_rpkg)

for i in psutil.disk_partitions():

print " \033[1;32m碟符: %s 掛載點: %s 使用率: %s%s\033[1;m" % (i[0],i[1],psutil.disk_usage(i[1])[3],bfh)

def net_io(s):

x = 0

sum = 0

while true:

if x >= s:

break

r1 = psutil.net_io_counters().bytes_recv

time.sleep(1)

r2 = psutil.net_io_counters().bytes_recv

y = r2 - r1

print "%.2f kb/s" % (y / 1024.0)

sum += y

x += 1

result = sum / x

print "\033[1;32m%s秒內平均速度:%.2f kb/s \033[1;m" % (x,result / 1024.0)

if __name__ == "__main__":

(options, args) = parser.parse_args()

if options.time:

net_io(int(options.time))

else:

sysinfo()

執行結果:

systeminfo.py -t 10使用:

1.18 kb/s

0.98 kb/s

1.11 kb/s

0.94 kb/s

0.89 kb/s

0.92 kb/s

1.29 kb/s

1.24 kb/s

1.21 kb/s

0.73 kb/s

10秒內平均速度:1.05 kb/s

python 獲取系統資訊

學python,用rpa www.i search.com.cn index.html?from line1 python 是跨平台語言,有時候我們的程式需要執行在不同系統上,例如 linux macos windows,為了使程式有更好通用性,需要根據不同系統使用不同操作方式。我們可以使用 pla...

python中獲取物件資訊

拿到乙個變數,除了用isinstance 判斷它是否是某種型別的例項外,還有沒有別的方法獲取到更多的資訊呢?例如,已有定義 class person object def init self,name,gender self.name name self.gender gender class st...

python 獲取E mail中的資訊

e mail主要由郵件頭和郵件體兩部分組成。郵件頭中的內容和我們寄信時寫在信封上的內容大同小意,當然這裡也包含了很多路過的 郵局 的資訊了。郵件體中的內容就是我們寫的信或者包裹。python自身包含了email模組處理可以快速的處理e mail中的資訊 import email 開啟乙個檔案 fp ...