1. 程式人生 > >python獲取系統基礎性能參數實現寫入文件

python獲取系統基礎性能參數實現寫入文件

default python 後臺運行 action import psutil

#!/usr/bin/env python
# coding:utf-8
import psutil
import time
import sys
from optparse import OptionParser
from datetime import date,datetime
import xlwt
import xlsxwriter
f = open("D:/1.txt", ‘w+‘)
parser = OptionParser()
parser.add_option("-t", "--time", dest="time",
                  help="此參數可查看當前下載占的帶寬,-t是測試時間", metavar="10")
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()))
    type(Boot_Start)
    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 >> f, " 開機時間:%s" % Boot_Start
    print >> f," CPU使用率:%s%s" % (Cpu_usage, BFH)
    print >> f,"內存:%dM\t內存使用率:%s%s" % (RAM, RAM_percent, BFH)
    print >> f,"交換分區內存:%dM\t交換分區使用率:%s%s" % (Swap, Swap_percent, BFH)
    print >> f," 發送:%d Byte\t發送包數:%d個" % (Net_sent, Net_spkg)
    print >>f," 接收:%d Byte\t接收包數:%d個" % (Net_recv, Net_rpkg)

    for i in psutil.disk_partitions():
        print >> f," 盤符: %s 掛載點: %s 磁盤使用率: %s%s" % (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 >> f,"1;33m%s秒內平均速度:%.2f Kb/s " % (x, result  /1024.0)


if __name__ == "__main__":
    (options, args) = parser.parse_args()
    if options.time:
        Net_io(int(options.time))
    else:
        Sysinfo()

最後結果

技術分享


由於才學,大神請多指導,謝謝,本來想直接想把結果插入excel中,目前還在研究,如有大神,請不吝賜教,感謝。

本文出自 “一杯水” 博客,請務必保留此出處http://6528161.blog.51cto.com/6518161/1932094

python獲取系統基礎性能參數實現寫入文件