简体   繁体   English

使用python在Windows计算机上运行的每个进程的cpu用法,内存,网络详细信息

[英]cpu usage ,memory , network details of each process running on windows machine using python

Hi Sorry I'm new to python. 嗨,抱歉,我是python的新手。 I'm not able to do this, I feel like it's easy but difficult to get the result so pls can anyone help me out this. 我无法做到这一点,我觉得要获得结果很容易但很困难,因此任何人都可以帮助我解决这个问题。

Here is my program and output (both actual and expected) 这是我的程序和输出(实际的和预期的)

import os, platform, subprocess, re 
import sys
import psutil
import itertools 
import json
import procs

class BaseProcessor(object):
    def __init__(self, name = "BaseProcessor"):
        self.name = name

    def processor(self):
        return self.proc

    def cpu_times(self):
        return self._base_cpu_times()

    def virtual_memory(self):
        return self._base_virtual_memory()

    def disk_io_counters(self):
        return self._base_disk_io_counters()

    def net_io_counters(self):
        return self._base_net_io_counters()

    def _init_proc(self):
        not_implemented

class PSUtilProcessor(BaseProcessor):
    def __init__(self, name = "PSUtilProcessor"):
        super().__init__(name)
        self.psutil = psutil
        self.proc = None
        if self._is_me():
            self._init_proc()

    def processor(self):
        return self.proc

    def _base_cpu_times(self):
        return { "overall" : self.psutil.cpu_times() }

    def _base_virtual_memory(self):
        return { "overall" : self.psutil.virtual_memory() }

    def _base_disk_io_counters(self):
        return { "overall" :  self.psutil.disk_io_counters() }

    def _base_net_io_counters(self):
        return { "overall" :  self.psutil.net_io_counters() }

    def _is_me(self):
        return platform.system() == self.name

    def _init_proc(self):
        not_implemented


class WinProcessor(PSUtilProcessor):
    def __init__(self):
        super().__init__("Windows")

    def _init_proc(self):
        self.proc = platform.processor()

    def monitor(pid):
        cpu_table =[]
        p = psutil.Process(pid)
        while p.is_running():
            cpu_table.append(p.get_cpu_percent())
            time.sleep(1)
        return cpu_table

class FileProcessor(BaseProcessor):
    def __init__(self):
        super().__init__("Simulator")

    def monitor(pid):
        cpu_table =[]
        p = psutil.Process(pid)
        while p.is_running():
            cpu_table.append(p.get_cpu_percent())
            time.sleep(1)
        return cpu_table

    def _base_cpu_times(self):
        rjson = { 'load from the file' }
        return rjson

class DarProcessor(PSUtilProcessor):
    def __init__(self):
        super().__init__("Darwin")

    def _init_proc(self):
        os.environ['PATH'] = os.environ['PATH'] + os.pathsep + '/usr/sbin'
        command ="sysctl -n machdep.cpu.brand_string"
        self.proc = subprocess.check_output(command).strip()

class LinProcessor(PSUtilProcessor):
    def __init__(self):
        super().__init__("Linux")

    def _init_proc(self):
        os.environ['PATH'] = os.environ['PATH'] + os.pathsep + '/usr/sbin'
        command = "cat /proc/cpuinfo"
        all_info = subprocess.check_output(command, shell=True).strip()
        for line in all_info.split("\n"):
            if "model name" in line:
                self.proc = re.sub( ".*model name.*:", "", line,1)

# PFactory returns instance of an processor object based on the platform:

class PFactory:
    def __init__(self):
        self.objs = {}
        self.objs["Windows"] = WinProcessor()
        self.objs["Darwin"] = DarProcessor()
        self.objs["Linux"] = LinProcessor()

    def getMyProcessor(self):
        if platform.system() in self.objs:
           return self.objs[platform.system()]
        return BaseProcessor()

# PFactoryInstance creates an exact one instance of the PFActory object
# to get instance, you need to do the following:
#      PFactoryInst.getInstance()

class PFactoryInst:
    inst = PFactory()
    @staticmethod
    def getInstance():
        return PFactoryInst.inst



class pretty:
    def print(self, json_object):
        print(json.dumps(json_object, sort_keys=True, indent=4, separators=(',', ': ')))

    def procc(self):
        proc = PFactoryInst.getInstance().getMyProcessor()
        return proc 

class process:
    def processcheck(self):
        for proc in psutil.process_iter():
            try:
                #pinfo = proc.as_dict(attrs=['pid', 'name'])    
                pinfo = proc.as_dict(attrs=['pid'])
                pinfo1 = proc.as_dict(attrs=[ 'name'])
            except psutil.NoSuchProcess:
                pass
            else:
                print(pinfo)
                #WinProcessor(PSUtilProcessor)
                processname = pinfo1['name'].split(".") [0] 
                print(processname)


if True:
                proc = pretty().procc()

                print("CPU times")
                pretty().print(proc.cpu_times())
                print("Virtual memory")
                pretty().print(proc.virtual_memory())
                print("disk_io_counters")
                pretty().print(proc.disk_io_counters())
                print("net_io_counters")
                pretty().print(proc.net_io_counters())

pretty.procc("system")
process.processcheck("system")

Actual output : 实际输出:

CPU times
{
    "overall": [
        5481.375,
        5862.203125,
        79719.484375,
        407.01564025878906,
        293.5625
    ]
}
Virtual memory
{
    "overall": [
        8459284480,
        4692054016,
        44.5,
        3767230464,
        4692054016
    ]
}
disk_io_counters
{
    "overall": [
        294267,
        282292,
        11056774144,
        7101620224,
        569959140,
        220317590
    ]
}
net_io_counters
{
    "overall": [
        3266163,
        31412196,
        14121,
        23535,
        0,
        0,
        0,
        0
    ]
}
{'pid': 0}
System Idle Process
{'pid': 4}
System
{'pid': 32}
SystemSettings
{'pid': 476}
winlogon
{'pid': 588}
smss
{'pid': 688}
svchost
{'pid': 744}
svchost
{'pid': 812}
csrss
{'pid': 908}
wininit
{'pid': 920}
csrss
{'pid': 984}
services
{'pid': 992}
lsass
{'pid': 1076}
dwm
{'pid': 1156}
svchost
{'pid': 1160}
svchost
{'pid': 1196}
svchost
{'pid': 1312}
svchost
{'pid': 1364}
EmsService
{'pid': 1372}
CMGShieldSvc
{'pid': 1380}
svchost
{'pid': 1484}
svchost
{'pid': 1508}
svchost
{'pid': 1552}
svchost
{'pid': 1640}
WUDFHost
{'pid': 1740}
igfxCUIService
{'pid': 1980}
SearchUI
{'pid': 2044}
RtkAudioService64
{'pid': 2064}
HidMonitorSvc
{'pid': 2104}
RAVBg64
{'pid': 2200}
mfevtps
{'pid': 2212}
enstart64
{'pid': 2220}
HipMgmt
{'pid': 2228}
VsTskMgr
{'pid': 2240}
cb
{'pid': 2256}
RAVBg64
{'pid': 2316}
FireSvc
{'pid': 2324}
ngvpnmgr
{'pid': 2452}
WUDFHost
{'pid': 2588}
jusched
{'pid': 2608}
o2flash
{'pid': 2852}
chrome
{'pid': 2864}
spoolsv
{'pid': 3052}
svchost
{'pid': 3060}
FrameworkService
{'pid': 3064}
svchost
{'pid': 3076}
mfemms
{'pid': 3108}
mqsvc
{'pid': 3116}
python
{'pid': 3196}
dasHost
{'pid': 3224}
chrome
{'pid': 3240}
sqlwriter
{'pid': 3280}
PFERemediation
{'pid': 3320}
notepad++
{'pid': 3324}
Titus
{'pid': 3352}
esif_uf
{'pid': 3372}
svchost
{'pid': 3384}
msdtc
{'pid': 3440}
vmms
{'pid': 3468}
ielowutil
{'pid': 3532}
chrome
{'pid': 3664}
mfevtps
{'pid': 3676}
GoogleCrashHandler64
{'pid': 3716}
mfeann
{'pid': 3988}
SearchProtocolHost
{'pid': 4076}
UcMapi
{'pid': 4132}
svchost
{'pid': 4436}
Titus
{'pid': 4444}
naPrdMgr
{'pid': 4476}
conhost
{'pid': 4520}
mfefire
{'pid': 4556}
UdaterUI
{'pid': 4628}
unsecapp
{'pid': 4736}
mcshield
{'pid': 5272}
PresentationFontCache
{'pid': 5280}
chrome
{'pid': 5380}
audiodg
{'pid': 5460}
Calculator
{'pid': 5608}
Apoint
{'pid': 5764}
taskhostw
{'pid': 5772}
esif_assist_64
{'pid': 5808}
sihost
{'pid': 5948}
cmd
{'pid': 6020}
WmiPrvSE
{'pid': 6112}
GoogleCrashHandler
{'pid': 6176}
explorer
{'pid': 6184}
CcmExec
{'pid': 6276}
NomadBranch
{'pid': 6300}
RtkNGUI64
{'pid': 6312}
chrome
{'pid': 6320}
unsecapp
{'pid': 6376}
chrome
{'pid': 6388}
WmiPrvSE
{'pid': 6408}
py
{'pid': 6500}
WmiPrvSE
{'pid': 6512}
WmiPrvSE
{'pid': 6524}
ApplicationFrameHost
{'pid': 6548}
McTray
{'pid': 6628}
igfxEM
{'pid': 6648}
RAVBg64
{'pid': 6704}
RuntimeBroker
{'pid': 6740}
igfxHK
{'pid': 6780}
igfxTray
{'pid': 6820}
SearchIndexer
{'pid': 6832}
chrome
{'pid': 7100}
CmRcService
{'pid': 7220}
DCCService
{'pid': 7304}
ApMsgFwd
{'pid': 7400}
ShellExperienceHost
{'pid': 7776}
ApntEx
{'pid': 7792}
chrome
{'pid': 7808}
conhost
{'pid': 7824}
hidfind
{'pid': 8068}
SCNotification
{'pid': 8084}
svchost
{'pid': 8128}
chrome
{'pid': 8132}
chrome
{'pid': 8216}
chrome
{'pid': 8244}
RAVBg64
{'pid': 8372}
svchost
{'pid': 8396}
jucheck
{'pid': 8444}
chrome
{'pid': 8448}
CmgSysTray
{'pid': 8572}
chrome
{'pid': 8708}
EmsServiceHelper
{'pid': 8780}
lync
{'pid': 8868}
OneDrive
{'pid': 8924}
StikyNot
{'pid': 9304}
lynchtmlconv
{'pid': 9676}
WmiPrvSE
{'pid': 9732}
chrome
{'pid': 9816}
SearchFilterHost
{'pid': 9976}
chrome
{'pid': 10032}
WmiPrvSE
{'pid': 10128}
chrome
{'pid': 10168}
conhost
{'pid': 11056}
chrome

Expected output: 预期产量:

I need to get the details of CPU, Memory and network I/O counter for each process (pid) running on the window machine (local system) but here we are getting overall CPU usage , memory details. 我需要获取在窗口计算机(本地系统)上运行的每个进程(pid)的CPU,内存和网络I / O计数器的详细信息,但是在这里,我们获得了总体CPU使用率,内存的详细信息。

As far as I know, you can monitor cpu and memory usage of individual process using python's psutil library. 据我所知,您可以使用python的psutil库监视单个进程的cpu内存使用情况 But for monitoring network i/o of individual process you will need to create a network driver for system which can filter the traffic for particular process. 但是,为了监视单个进程的网络I / O ,您将需要为系统创建一个网络驱动程序,该驱动程序可以过滤特定进程的流量。 Refer 参考

Here's the solution for memory and cpu usage by process - 这是按进程使用内存和cpu的解决方案-

import psutil

# For Windows
process_data = {}
for proc in psutil.process_iter():
    print(proc.name())
    process_names[proc.name()] = {'cpu' : proc.cpu_percent(), 'memory': proc.memory_info()}

# For Linux
process_data = {}
for proc in psutil.process_iter():
    print(proc.name())
    process_names[proc.name()] = {'cpu' : proc.cpu_percent(), 'memory': proc.memory_full_info()}

print(process_data)
=> 
{
   'AGSService.exe': 
    {
        'cpu': 0.0,
        'memory': pmem(rss=8949760, vms=3072000, num_page_faults=2589, 
                  peak_wset=8994816, wset=8949760, peak_paged_pool=113696, 
                  paged_pool=111920, peak_nonpaged_pool=17296, 
                  nonpaged_pool=15080, pagefile=3072000,     
                  peak_pagefile=3244032, private=3072000)
     },
 ...}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM