1

认为这是我在这里提出的第一个问题,通常会找到我需要的所有答案(提前致谢)

好的,我的问题我已经编写了一个 python 程序,它将在线程中监视进程并将结果输出到 csv 文件以供以后使用。这段代码运行良好,我使用 win32pdhutil 作为计数器,使用 WMI,Win32_PerfRawData_PerfProc_Process 作为 CPU %time。我现在被要求监视 WPF 应用程序并专门监视用户对象和 GDI 对象。

这就是我遇到的问题,我似乎找不到任何 python 支持来收集这两个计数器上的指标。这两个计数器在任务管理器中很容易获得我觉得奇怪的是这两个计数器的信息很少。我正在专门研究收集这些以查看我们是否有内存泄漏,我不想在系统上安装除已安装的 python 之外的任何其他东西。请您帮忙寻找解决方案。

我正在使用 python 3.3.1,它将在 Windows 平台上运行(主要是 win7 和 win8)这是我用来收集数据的代码

def gatherIt(self,whoIt,whatIt,type,wiggle,process_info2):
    #this is the data gathering function thing
    data=0.0
    data1="wobble"
    if type=="counter":
        #gather data according to the attibutes
        try:
            data = win32pdhutil.FindPerformanceAttributesByName(whoIt, counter=whatIt)
        except:
            #a problem occoured with process not being there not being there....
            data1="N/A"

    elif type=="cpu":
       try:
            process_info={}#used in the gather CPU bassed on service
            for x in range(2):
                for procP in wiggle.Win32_PerfRawData_PerfProc_Process(name=whoIt):
                    n1 = int(procP.PercentProcessorTime)
                    d1 = int(procP.Timestamp_Sys100NS)
                    #need to get the process id to change per cpu look...
                    n0, d0 = process_info.get (whoIt, (0, 0))     
                    try:
                        percent_processor_time = (float (n1 - n0) / float (d1 - d0)) *100.0
                        #print whoIt, percent_processor_time
                    except ZeroDivisionError:
                        percent_processor_time = 0.0
                    # pass back the n0 and d0
                    process_info[whoIt] = (n1, d1)
                #end for loop (this should take into account multiple cpu's)
            # end for range to allow for a current cpu time rather that cpu percent over sampleint
            if percent_processor_time==0.0:
                data=0.0
            else:
                data=percent_processor_time
        except:
            data1="N/A"

    else:
        #we have done something wrong so data =0
        data1="N/A"
    #endif
    if data == "[]":
        data=0.0
        data1="N/A"
    if data == "" :
        data=0.0
        data1="N/A"
    if data == " ":
        data=0.0
        data1="N/A"
    if data1!="wobble" and data==0.0:
        #we have not got the result we were expecting so add a n/a
        data=data1
    return data

干杯

如果有人试图运行它,则编辑正确的 cpu 计时问题:D

4

2 回答 2

3

因此,经过长时间的搜索,我能够将一些东西混合在一起,从而为我提供所需的信息。

import time
from ctypes import *
from ctypes.wintypes import *
import win32pdh

# with help from here http://coding.derkeiler.com/Archive/Python/comp.lang.python/2007-10/msg00717.html
# the following has been mashed together to get the info needed

def GetProcessID(name):
    object = "Process"
    items, instances = win32pdh.EnumObjectItems(None, None, object, win32pdh.PERF_DETAIL_WIZARD)
    val = None
    if name in instances :
        tenQuery = win32pdh.OpenQuery()
        tenarray = [ ]
        item = "ID Process"
        path = win32pdh.MakeCounterPath( ( None, object, name, None, 0, item ) )
        tenarray.append( win32pdh.AddCounter( tenQuery, path ) )
        win32pdh.CollectQueryData( tenQuery )
        time.sleep( 0.01 )
        win32pdh.CollectQueryData( tenQuery )
        for tencounter in tenarray:
            type, val = win32pdh.GetFormattedCounterValue( tencounter, win32pdh.PDH_FMT_LONG )
            win32pdh.RemoveCounter( tencounter )
        win32pdh.CloseQuery( tenQuery )
    return val

processIDs = GetProcessID('OUTLOOK') # Remember this is case sensitive
PQI = 0x400
#open a handle on to the process so that we can query it
OpenProcessHandle = windll.kernel32.OpenProcess(PQI, 0, processIDs)
# OK so now we have opened the process now we want to query it
GR_GDIOBJECTS, GR_USEROBJECTS = 0, 1
print(windll.user32.GetGuiResources(OpenProcessHandle, GR_GDIOBJECTS))
print(windll.user32.GetGuiResources(OpenProcessHandle, GR_USEROBJECTS))
#so we have what we want we now close the process handle
windll.kernel32.CloseHandle(OpenProcessHandle)

希望有帮助

于 2013-08-13T11:12:47.833 回答
2

对于 GDI 计数,我认为一个更简单、更干净的监控脚本如下:

import time, psutil
from ctypes import *

def getPID(processName):
    for proc in psutil.process_iter():
        try:
            if processName.lower() in proc.name().lower():
                return proc.pid
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass
    return None;

def getGDIcount(PID):
    PH = windll.kernel32.OpenProcess(0x400, 0, PID)
    GDIcount = windll.user32.GetGuiResources(PH, 0)
    windll.kernel32.CloseHandle(PH)
    return GDIcount

PID = getPID('Outlook')

while True:
    GDIcount = getGDIcount(PID)
    print(f"{time.ctime()}, {GDIcount}")
    time.sleep(1)
于 2019-07-10T02:26:23.067 回答