自制模块包 ::-- ZoomQuiet [2007-09-03 04:52:28]

CPUG联盟::

CPUG::门户plone

BPUG

SPUG

ZPUG

SpreadPython Python宣传

1. cpu,内存和网络的使用率

{{{Qiangning Hong <[email protected]> hide details 11:29 am (35 minutes ago)

On 9/3/07, 边 江 <[email protected]> wrote: > 想用python写个得到cpu,内存和网络的使用率的小程序,主要在windows系统中,要是可以跨平台最好不过。 > > 不知道python自带的有没有这个lib,要是没有能不能推荐个lib。 }}}

很久以前写的代码,在windows下获得CPU和内存使用情况:

   1 import win32pdh
   2 
   3 # Counter paths
   4 PROCESSOR_PERCENT = r'\Processor(_Total)\% Processor Time'
   5 MEMORY_PERCENT = r'\Memory\% Committed Bytes In Use'
   6 MEMORY_COMMITTED = r'\Memory\Committed Bytes'
   7 PROCESS_BYTES = lambda x: r'\Process(%s)\Private Bytes' % x
   8 
   9 class Query:
  10     def __init__(self):
  11         self.counters = {}
  12         self.query = None
  13         self.query = win32pdh.OpenQuery(None, 0)
  14 
  15     def add_counter(self, path):
  16         if win32pdh.ValidatePath(path) != 0:
  17             raise Exception('Invalid path: %s' % path)
  18         counter = win32pdh.AddCounter(self.query, path, 0)
  19         self.counters[path] = counter
  20 
  21     def remove_counter(self, path):
  22         win32pdh.RemoveCounter(self.counters[path])
  23         del self.counters[path]
  24 
  25     def get_values(self):
  26         values = {}
  27         win32pdh.CollectQueryData(self.query)
  28         for path in self.counters:
  29             status, value = win32pdh.GetFormattedCounterValue(
  30                     self.counters[path], win32pdh.PDH_FMT_LONG)
  31             values[path] = value
  32         return values
  33 
  34 sysinfo_query = Query()
  35 sysinfo_query.add_counter(PROCESSOR_PERCENT)
  36 sysinfo_query.add_counter(MEMORY_PERCENT)
  37 sysinfo_query.get_values()
  38 
  39 def get_sysinfo():
  40     """Return a tuple (mem_usage, cpu_usage)."""
  41     info = sysinfo_query.get_values()
  42     return info[MEMORY_PERCENT], info[PROCESSOR_PERCENT]

*nix系统下,用管道分析 uptime 和 free 命令的输出就可以了。

MicroProj/2007-09-03 (last edited 2009-12-25 07:14:23 by localhost)