psutil - A cross-platform process and system utilities module for Python

1. 安装

pip 安装即可。

windows 下需要安装 vs2008,否则报错: Unable to find vcvarsall.bat

如果已经安装 vs2010 / vs2012 则需要设置环境变量,VS90COMNTOOLS 指向已有的 vs 变量。

vs2010 设置如下:

  1. VS90COMNTOOLS = %VS100COMNTOOLS%

2. 获取特定进程对象

  • 根据进程 ID 创建进程对象
  • 获取所有进程对象,过滤出目标进程
  1. # -*- coding: utf-8-*-
  2. import psutil
  3.  
  4. def get_proc_by_id(pid):
  5. return psutil.Process(pid)
  6.  
  7. def get_proc_by_name(pname):
  8. """ get process by name
  9.  
  10. return the first process if there are more than one
  11. """
  12. for proc in psutil.process_iter():
  13. try:
  14. if proc.name().lower() == pname.lower():
  15. return proc # return if found one
  16. except psutil.AccessDenied:
  17. pass
  18. except psutil.NoSuchProcess:
  19. pass
  20. return None
  21.  
  22. if '__main__' == __name__:
  23. print get_proc_by_name("chrome.exe")
  24. print get_proc_by_id(4364)

3. 获取进程信息

3.1 需要特别注意异常保护,尤其是  psutil.AccessDenied

不同的进程,权限等信息可能不同,遍历所有进程取信息时,需要对每一个进程单独进程异常保护。

3.2 获取所有进程

大多数 demo 代码中,都是使用  psutil.get_process_list ,但该方法在源码中已经标记为废弃。

新推荐的是  psutil.process_iter 迭代器。

根据下面的源码可知实现原理:获取所有进程 ID,然后根据 ID 创建进程对象。

  1. _pmap = {}
  2.  
  3. def process_iter():
  4. """Return a generator yielding a Process class instance for all
  5. running processes on the local machine.
  6.  
  7. Every new Process instance is only created once and then cached
  8. into an internal table which is updated every time this is used.
  9.  
  10. Cached Process instances are checked for identity so that you're
  11. safe in case a PID has been reused by another process, in which
  12. case the cached instance is updated.
  13.  
  14. The sorting order in which processes are yielded is based on
  15. their PIDs.
  16. """
  17. def add(pid):
  18. proc = Process(pid)
  19. _pmap[proc.pid] = proc
  20. return proc
  21.  
  22. def remove(pid):
  23. _pmap.pop(pid, None)
  24.  
  25. a = set(get_pid_list())
  26. b = set(_pmap.keys())
  27. new_pids = a - b
  28. gone_pids = b - a
  29.  
  30. for pid in gone_pids:
  31. remove(pid)
  32. for pid, proc in sorted(list(_pmap.items()) + \
  33. list(dict.fromkeys(new_pids).items())):
  34. try:
  35. if proc is None: # new process
  36. yield add(pid)
  37. else:
  38. # use is_running() to check whether PID has been reused by
  39. # another process in which case yield a new Process instance
  40. if proc.is_running():
  41. yield proc
  42. else:
  43. yield add(pid)
  44. except NoSuchProcess:
  45. remove(pid)
  46. except AccessDenied:
  47. # Process creation time can't be determined hence there's
  48. # no way to tell whether the pid of the cached process
  49. # has been reused. Just return the cached version.
  50. yield proc
  51. @_deprecated()
  52. def get_process_list():
  53. """Return a list of Process class instances for all running
  54. processes on the local machine (deprecated).
  55. """
  56. return list(process_iter())

3.3 进程的内存信息 -- VSS/RSS/PSS/USS

VSS 是剩余的可访问内存。

进程占用内存包括 2 部分,自身 + 共享库。不同的算法产生了 3 个不同的内存指标,分别是:RSS / PSS / USS。

一般来说内存占用大小有如下规律:VSS >= RSS >= PSS >= USS

Demo 代码如下

  1. proc = psutil.Process(4364)
  2.  
  3. total = psutil.virtual_memory().total
  4. rss, vss = proc.memory_info()
  5. percent = proc.memory_percent()
  6.  
  7. print "rss: %s Byte, vss: %s Byte" % (rss, vss)
  8. print "total: %.2f(M)" % (float(total)/1024/1024/1024)
  9. print "percent: %.2f%%, calc: %.2f%%" % (percent, 100*float(rss)/total)

输出

本机内存信息截图

详细说明:

  • VSS(reported as VSZ from ps) is the total accessible address space of a process. 
    This size also includes memory that may not be resident in RAM like mallocs that have been allocated but not written to.
    VSS is of very little use for determing real memory usage of a process.
  • RSS is the total memory actually held in RAM for a process.
    RSS can be misleading, because it reports the total all of the shared libraries that the process uses,
    even though a shared library is only loaded into memory once regardless of how many processes use it.
    RSS is not an accurate representation of the memory usage for a single process.
  • PSS differs from RSS in that it reports the proportional size of its shared libraries,
    i.e. if three processes all use a shared library that has 30 pages,
    that library will only contribute 10 pages to the PSS that is reported for each of the three processes.
    PSS is a very useful number because when the PSS for all processes in the system are summed together,
    that is a good representation for the total memory usage in the system.
    When a process is killed, the shared libraries that contributed to its PSS
    will be proportionally distributed to the PSS totals for the remaining processes still using that library.
    In this way PSS can be slightly misleading, because
    when a process is killed, PSS does not accurately represent the memory returned to the overall system.
  • USS is the total private memory for a process,
    i.e. that memory that is completely unique to that process.
    USS is an extremely useful number because it indicates the true incremental cost of running a particular process.
    When a process is killed, the USS is the total memory that is actually returned to the system.
    USS is the best number to watch when initially suspicious ofmemory leaksin a process.

win/linux 下使用 psutil 获取进程 CPU / memory / IO 占用信息的更多相关文章

  1. linux下使用taskset设置进程cpu绑定不起作用

    自从大规模使用了虚拟化之后,大流量时soft interrupt在某个cpu很高就是个严重的问题,最近一有时间就研究这个问题,如果网卡本身不支持多队列的话,有没有办法缓解这个问题. 一开始使用rps, ...

  2. Linux下用程序实现统计cpu和内存的利用率

    Linux下没有直接可以调用系统函数知道CPU占用和内存占用.那么如何知道CPU和内存信息呢.只有通过proc伪文件系统来实现. proc伪文件就不介绍了,只说其中4个文件.一个是/proc/stat ...

  3. Linux下用C获取当前时间

    Linux下用C获取当前时间,具体如下: 代码(可以把clock_gettime换成time(NULL)) ? 1 2 3 4 5 6 7 8 9 10 void getNowTime() {  ti ...

  4. Linux下查看某一进程所占用内存的方法

    Linux下查看某一个进程所占用的内存,首先可以通过ps命令找到进程id,比如 ps -ef | grep kafka 可以看到kafka这个程序的进程id 可以看到是2913,现在可以使用如下命令查 ...

  5. linux中使用top获取进程的资源占用信息

    在linux中使用top获取进程的资源占用信息: Cpu(s):  1.0%us,  0.0%sy,  0.0%ni, 98.3%id,  0.7%wa,  0.0%hi,  0.0%si,  0.0 ...

  6. linux ps命令,查看某进程cpu和内存占用率情况, linux ps命令,查看进程cpu和内存占用率排序。 不指定

    背景:有时需要单看某个进程的CPU及占用情况,有时需要看整体进程的一个占用情况.一. linux ps命令,查看某进程cpu和内存占用率情况[root@test vhost]# ps auxUSER  ...

  7. linux下dmidecode命令获取硬件信息

    linux下dmidecode命令获取硬件信息 2 A+ 所属分类:Linux 运维工具 dmidecode在 Linux 系统下获取有关硬件方面的信息.dmidecode 遵循 SMBIOS/DMI ...

  8. 获取进程CPU占用率

    获取进程CPU占用率 // 时间转换 static __int64 file_time_2_utc(const FILETIME* ftime) { LARGE_INTEGER li; li.LowP ...

  9. Linux 下监控用户最大进程数参数(nproc)是否到达上限

    Linux 下监控用户最大进程数参数(nproc)是否到达上限的步骤: 1.查看各系统用户的进程(LWP)数: 注意:默认情况下采用 ps 命令并不能显示出所有的进程.因为 Linux 环境下执行多线 ...

随机推荐

  1. cocos2d-x Animation

    转自:http://codingnow.cn/cocos2d-x/810.html 这一篇来学习怎么使用cocos2d-x引擎播放帧动画,就是把一帧一帧的图片像电影那样显示出来.1. 首先来了解一下相 ...

  2. cocos2d-x Action

    转自:http://codingnow.cn/cocos2d-x/775.html 从结构图可以看出,动作类的基类是CCAction,通过继承它可以实现很多种动作. CCFiniteTimeActio ...

  3. 从零开始学android-一行两个按钮居中 布局

    方法一: <RelativeLayout android:id="@+id/relativeTop" android:layout_width="fill_pare ...

  4. Windows下配置PHP支持LDAP扩展方法(wampserver)

    在网上搜了好多文章都不行呢,大都是没有开启扩展的问题,可是我的是开启的. 终于看到一篇文章,因为我用的是wampserver.下面是文章原话: 然后你发现上面的提示依旧,因为这是网上大多能查到的资料的 ...

  5. Android ADB使用之详细篇

    Android开发环境中,ADB是我们进行Android开发经常要用的调试工具,它的使用当然是我们Android开发者必须要掌握的. ADB概述 Android Debug Bridge,Androi ...

  6. sphinx的简单实例

    sphinx.conf中的配置: source indexLocation { type = mysql sql_host = 192.168.1.113 sql_user = root sql_pa ...

  7. PHP中获取中英文混合字符串长度[主要是指个数,而不是字符串长度](转)

    今晚在写框架的表单验证类时,需要判断某个字符串长度是否在指定区间内,很自然地,想到了PHP中的strlen函数. $str = 'Hello world!'; echo strlen($str);   ...

  8. IaaS层市场科普

    简介 这是本博客系列云计算相关文章中的第二篇,所有文章请参考: 博客所有文章 本文主要介绍了一下当前IaaS层市场上的几个主要角色,这几个角色的历史发展以及现状. 开源市场 CloudStack 一句 ...

  9. windows远程关机重启

    windows远程关机 http://lsscto.blog.51cto.com/779396/245681 shutdown http://baike.baidu.com/view/596875.h ...

  10. java_Cookies_1_商品浏览历史记录servlet1

    public class CookiesServlet1 extends HttpServlet { public void doGet(HttpServletRequest request, Htt ...