Python获取指定服务的cpu占用率。求高手指教,我的代码运行不出来

渔樵者 2015-01-24 02:59:57
以下是我的两个文件,希望大神或者喜欢尝试的兄弟看看。
高手看看看,我的代码没有运行出来,我目前也不知道是什么问题。
test_no1.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-

import ctypes;
import psutil
import test_no2
__metaclass__ = type;

class PROCESSENTRY32(ctypes.Structure):
_fields_ = [
("dwSize",ctypes.c_ulong),
("cntUsage",ctypes.c_ulong),
("th32ProcessID",ctypes.c_ulong),
("th32DefaultHeapID",ctypes.c_void_p),
("th32ModuleID",ctypes.c_ulong),
("cntThreads",ctypes.c_ulong),
("th32ParentProcessID",ctypes.c_ulong),
("pcPriClassBase",ctypes.c_long),
("dwFlags",ctypes.c_ulong),
("szExeFile",ctypes.c_char*260)
]

kernel32 = ctypes.windll.LoadLibrary("kernel32.dll");
pHandle = kernel32.CreateToolhelp32Snapshot(0x2,0x0);

import sys;

if pHandle==-1:
sys.exit();

proc = PROCESSENTRY32();
proc.dwSize = ctypes.sizeof(proc);

while kernel32.Process32Next(pHandle,ctypes.byref(proc)):
ss = ctypes.string_at(proc.szExeFile)
ss=str(ss)
ss=ss.strip("b'")
if ss == "Tra_ser.exe":#获取此服务的cpu占用率
proc_PID = proc.th32ProcessID
print(proc.th32ProcessID)
p = psutil.Process(proc.th32ProcessID)
p.get_cpu_percent(interval=0)
print("####")
print(p.get_cpu_percent(interval=0))#第一次调用
print("####")

kernel32.CloseHandle(pHandle);

#TODO:test_no2的函数接口
test_no2.test(proc_PID)

test_no2.py
import psutil

def test(a):
p1 = psutil.Process(a)
cpu_per = p1.get_cpu_percent(interval=0)#再次调用获取cpu占用率
print("我到达被启动函数,下面打印进程cpu使用率")
print(cpu_per)
...全文
250 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
DarkChampion 2015-01-25
  • 打赏
  • 举报
回复
我跑了下,好像没问题啊, 当然,我把Tra_ser.exe换成pythonw.exe了。你确认有Tra_ser.exe这个进程吗
7636
####
0.0
####
我到达被启动函数,下面打印进程cpu使用率
0.0
panghuhu250 2015-01-25
  • 打赏
  • 举报
回复

        p = psutil.Process(proc.th32ProcessID)
        p.get_cpu_percent(interval=0)
        print("####")
        print(p.get_cpu_percent(interval=0))#第一次调用
两次get_cpu_percent之间要等一段时间, 或者干脆用p.get_cpu_percent(interval=0.5). psutil文档里说: psutil.cpu_percent(interval=None, percpu=False) Return a float representing the current system wide CPU utilization as a percentage. When interval is > 0.0 compares system CPU times elapsed before and after the interval (blocking). When interval is 0.0 or None compares system CPU times elapsed since last call or module import, returning immediately. That means the first time this is called it will return a meaningless 0.0 value which you are supposed to ignore. In this case is recommended for accuracy that this function be called with at least 0.1 seconds between calls. 另外, psutil有psutil.process_iter()可以列出所有的process, 而且可以跨平台使用.不需要用kernel32的函数(当然, process_iter()可能调用了kernel32).

37,720

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧