Pazar, Aralık 22, 2024

Python İle Sistem Bilgilerinin Sorgulanması

Elinde python yazılı kağıt tutan bir hintli yazılımcı

Yaptığınız uygulamada CPU, Memory, Network ve Disk bilgilerini kullanıcılara göstermek isteyebilirsiniz veya sistemin genel durumunu kontrol etmek için geliştirmeler yapabilirsiniz. psutil aracılığı ile bu ve buna benzer bilgileri topladığımız kodumuz şu şekildedir.

import psutil
import json

def bytes2human(n):
    symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
    prefix = {}
    for i, s in enumerate(symbols):
        prefix[s] = 1 << (i + 1) * 10
    for s in reversed(symbols):
        if n >= prefix[s]:
            value = float(n) / prefix[s]
            return '%.1f%s' % (value, s)
    return "%sB" % n


class cpuInfo():

    def __init__(self):
        self.info =  {}
        self.cpu_percentage()
        self.cpu_count()
        self.cpu_freq()

    def cpu_percentage(self):
        perct = psutil.cpu_percent(interval=0.5,percpu=True)
        cpuinfo = {}
        for i in range(0,len(perct)):
            cpuinfo['Core {}'.format(i)] = perct[i]
        self.info['CPU Usages'] = cpuinfo

    def cpu_count(self):
        self.info['Psychical CPU Core'] = psutil.cpu_count(logical=False)
        self.info['CPU Count'] = psutil.cpu_count()

    def cpu_freq(self):
        freq = psutil.cpu_freq(percpu=True)
        freq_info = {}
        for i in range(len(freq)):
            freq_info["CPU {}".format(i)] = {'Max':freq[i].max,'Current':freq[i].current}
        self.info['CPU Frequency'] = freq_info

    def collectioner(self):
        return json.dumps(self.info)

class memoryInfo():

    def __init__(self):
        self.info = {}
        self.meminfo()
        self.swapinfo()

    def meminfo(self):
        mem = psutil.virtual_memory()
        total = bytes2human(mem.total)
        used = bytes2human(mem.used)
        free=  bytes2human(mem.total - mem.used)
        perc = mem.percent
        self.info['Pysical Memory'] = {'Total':total,'Used':used,'Free':free,'Percentage':perc}

    def swapinfo(self):
        mem = psutil.swap_memory()
        total = bytes2human(mem.total)
        used = bytes2human(mem.used)
        free = bytes2human(mem.free)
        perc = mem.percent
        self.info['Swap Memory'] = {'Total': total, 'Used': used, 'Free': free, 'Percentage': perc}

    def collectioner(self):
        return json.dumps(self.info)

class hddInfo():

    def __init__(self):
        self.info = {}
        self.hddGeneral()

    def hddGeneral(self):
        hdd = psutil.disk_partitions()
        hddinfo  = {}
        for h in range(len(hdd)):
            hddinfo['DISK{}'.format(h)] = {'Disk Type:':hdd[h].fstype, 'Device Name':hdd[h].device, 'Disk Usage':self.hddUsage(hdd[h].mountpoint)}
        self.info['DISK Properties'] = hddinfo

    def hddUsage(self,hddName):
        info = {}
        hdd = psutil.disk_usage(hddName)
        info['Disk Usage'] = bytes2human(hdd.used)
        info['Total'] = bytes2human(hdd.total)
        info['Free'] = bytes2human(hdd.free)
        info['Percentage'] = bytes2human(hdd.percent)
        return info

    def collectioner(self):
        return json.dumps(self.info)

class NetworkInfo():

    def __init__(self):
        self.info = {}
        self.networkTraffic()
        self.failedNetwork()

    def networkTraffic(self):
        networks = {}
        net = psutil.net_io_counters(pernic=True)
        for n in net:
            networks[n] = {'Bytes Recv': bytes2human(net[n].bytes_recv),'Bytes Send':bytes2human(net[n].bytes_sent)}
        self.info['Success Network Traffic'] = networks

    def failedNetwork(self):
        networks = {}
        net = psutil.net_io_counters(pernic=True)
        for n in net:
            networks[n] = {'Dropped Inner Packets': net[n].dropin, 'Dropped Outter Packets': net[n].dropout}
        self.info['Dropped Network Traffics'] = networks

    def collectioner(self):
        return json.dumps(self.info)

print(cpuInfo())