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 设置如下:

VS90COMNTOOLS = %VS100COMNTOOLS%

2. 获取特定进程对象

  • 根据进程 ID 创建进程对象
  • 获取所有进程对象,过滤出目标进程
# -*- coding: utf-8-*-
import psutil def get_proc_by_id(pid):
return psutil.Process(pid) def get_proc_by_name(pname):
""" get process by name return the first process if there are more than one
"""
for proc in psutil.process_iter():
try:
if proc.name().lower() == pname.lower():
return proc # return if found one
except psutil.AccessDenied:
pass
except psutil.NoSuchProcess:
pass
return None if '__main__' == __name__:
print get_proc_by_name("chrome.exe")
print get_proc_by_id(4364)

3. 获取进程信息

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

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

3.2 获取所有进程

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

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

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

_pmap = {}

def process_iter():
"""Return a generator yielding a Process class instance for all
running processes on the local machine. Every new Process instance is only created once and then cached
into an internal table which is updated every time this is used. Cached Process instances are checked for identity so that you're
safe in case a PID has been reused by another process, in which
case the cached instance is updated. The sorting order in which processes are yielded is based on
their PIDs.
"""
def add(pid):
proc = Process(pid)
_pmap[proc.pid] = proc
return proc def remove(pid):
_pmap.pop(pid, None) a = set(get_pid_list())
b = set(_pmap.keys())
new_pids = a - b
gone_pids = b - a for pid in gone_pids:
remove(pid)
for pid, proc in sorted(list(_pmap.items()) + \
list(dict.fromkeys(new_pids).items())):
try:
if proc is None: # new process
yield add(pid)
else:
# use is_running() to check whether PID has been reused by
# another process in which case yield a new Process instance
if proc.is_running():
yield proc
else:
yield add(pid)
except NoSuchProcess:
remove(pid)
except AccessDenied:
# Process creation time can't be determined hence there's
# no way to tell whether the pid of the cached process
# has been reused. Just return the cached version.
yield proc
@_deprecated()
def get_process_list():
"""Return a list of Process class instances for all running
processes on the local machine (deprecated).
"""
return list(process_iter())

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

VSS 是剩余的可访问内存。

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

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

Demo 代码如下

proc = psutil.Process(4364)

total = psutil.virtual_memory().total
rss, vss = proc.memory_info()
percent = proc.memory_percent() print "rss: %s Byte, vss: %s Byte" % (rss, vss)
print "total: %.2f(M)" % (float(total)/1024/1024/1024)
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. MySQL5日期类型DATETIME和TIMESTAMP相关问题详解

    MySQL5日期类型DATETIME和TIMESTAMP相关问题详解 MySQL5的日期类型有三种:DATETIME.DATE和TIMESTAMP,除了DATE用来表示一个不带时分秒的是日期,另外两个 ...

  2. Lync边缘服务器配置

    以下步骤均使用Lync管理员权限即可完成 1.在前端下载并编辑拓扑,新建边缘池 如果边缘池中只有一台服务器,则池名称与服务器名称相同,如下: 如果需要删除边缘池,则需要先取消关联,如下: 2.发布拓扑 ...

  3. [Arduino+Android] 自制土砲智能安全帽

    专案动机(1/2) .现今社会中,各种交通运输载具方便了人类的生活,缩小了地域的差异性,当中车辆是人们日常生活中最频繁接触到的一部分. .车辆使人们的行动更加便利,也因此道路上行驶的车辆越来越多. . ...

  4. 基于反射实现自己主动化restful开发

    [Author]: kwu 基于反射实现自己主动化restful开发,通用的仅仅须要写查询数据库的sql.并增加相应的javabean实现的高速restful服务的开发. 1.编写数据库的查询sql. ...

  5. mysql控制流程函数

    1.case语句 select case 2 when 1 then '男' when 2 then '女' else 'xoap' end as result; 2.if语句 select if(1 ...

  6. python--介绍

    语言类型介绍 编译与解释理解: 打个比方:假如你打算阅读一本外文书,而你不知道这门外语,那么你可以找一名翻译,给他足够的时间让他从头到尾把整本书翻译好,然后把书的母语版交给你阅读:或者,你也立刻让这名 ...

  7. oracle的sql函数

    只读事务set transaction read only当一个用户添加了只读事务,则查询时只会查到设置只读事务之前的内容,在并发量大的系统中,通过设置只读事务 便于统计 oracle的sql函数的使 ...

  8. 命令行界面下的用户和组管理之usermod的使用

    当使用useradd添加好用户之后,想要做一些修改,这时需要用到usermod命令. 功能说明:修改用户帐号的各项信息. 语 法:usermod [-L | U][-c <备注>][-d ...

  9. CyclicBarrier 使用说明

    字面意思回环栅栏,通过它可以实现让一组线程等待至某个状态之后再全部同时执行.叫做回环是因为当所有等待线程都被释放以后,CyclicBarrier可以被重用.   主要方法:      public i ...

  10. Servlet线程安全问题

    Servlet采用单实例多线程方式运行,因此是线程不安全的.默认情况下,非分布式系统,Servlet容器只会维护一个Servlet的实例,当多个请求到达同一个Servlet时,Servlet容器会启动 ...