psutil (Python 系统和进程实用工具) 是跨平台库用于检索信息当运行 processes and 系统利用率 (CPU、内存、磁盘、网络、传感器) 在 Python 。它很有用主要用于 系统监视 , 剖分析 , 限制进程资源 和 运行进程的管理 。它实现了由 UNIX 命令行工具提供的许多功能,譬如: ps, top, lsof, netstat, ifconfig, who, df, kill, free, nice, ionice, iostat, iotop, uptime, pidof, tty, taskset, pmap 。psutil 目前支持以下平台:
支持 Python 版本 2.7 and 3.4+ . PyPy 已知也能工作。
您正在阅读的 psutil 文档编制以单 HTML 页面形式分发。
虽然 psutil 是自由软件且始终是,但工程有一些基金将获益匪浅。就我个人时间而言,保持 Bug 报告和维护已变得难以为继。若您是大量使用 psutil 的公司,可以考虑变为赞助者凭借 GitHub , 开放集体 or PayPal 且你的 Logo 将显示在这里和 psutil doc .
在 Linux、Windows、macOS:
pip install psutil
对于其它平台,见更详细的 安装 指导。
psutil.
cpu_times
(
percpu=False
)
¶
以命名元组形式返回系统 CPU 时间。每个属性表示 CPU 在给定模式下度过的秒数。属性的可用性因平台而异:
特定平台字段:
当
percpu
is
True
返回系统中每个逻辑 CPU 的命名元组列表。列表中的第一个元素是指第一个 CPU,第二个元素是指第二个 CPU,依此类推。列表次序跨调用保持一致。Linux 中的输出范例:
>>> import psutil >>> psutil.cpu_times() scputimes(user=17411.7, nice=77.99, system=3797.02, idle=51266.57, iowait=732.58, irq=0.01, softirq=142.43, steal=0.0, guest=0.0, guest_nice=0.0)
4.1.0 版改变: 添加 interrupt and dpc 字段在 Windows。
警告
假设 CPU 时间始终随时间递增,或至少保持不变,这是因为时间无法倒退。出人意料,有时情况可能并非如此 (至少在 Windows 和 Linux),见 #1210 .
psutil.
cpu_percent
(
interval=None
,
percpu=False
)
¶
以百分比形式返回表示当前系统范围 CPU 利用率的浮点数。当
interval
>
0.0
比较间隔 (阻塞) 前后的系统 CPU 消耗时间。当
interval
is
0.0
or
None
比较从最后调用 (或模块导入) 起的系统 CPU 消耗时间,立即返回。意味着首次调用时,这会返回无意义
0.0
值假设要忽略。在这种情况下的推荐精度,是调用此函数至少间隔
0.1
秒在调用之间。当
percpu
is
True
返回表示各 CPU 利用率,按百分比形式的浮点数列表。列表中的第一个元素是指第一个 CPU,第二个元素是指第二个 CPU,依此类推。列表次序跨调用保持一致。
>>> import psutil >>> # blocking >>> psutil.cpu_percent(interval=1) 2.0 >>> # non-blocking (percentage since last call) >>> psutil.cpu_percent(interval=None) 2.9 >>> # blocking, per-cpu >>> psutil.cpu_percent(interval=1, percpu=True) [2.0, 1.0] >>>
警告
首次调用此函数采用
interval
=
0.0
or
None
它将返回无意义
0.0
值假设要忽略。
psutil.
cpu_times_percent
(
interval=None
,
percpu=False
)
¶
如同
cpu_percent()
但以百分比形式为每个特定 CPU 时间提供利用率,返回通过
psutil.cpu_times(percpu=True)
.
interval
and
percpu
自变量拥有相同含义如在
cpu_percent()
。在 Linux guest 和 guest_nice 百分比不计入 user 和 user_nice 百分比。
警告
首次调用此函数采用
interval
=
0.0
or
None
它将返回无意义
0.0
值假设要忽略。
4.1.0 版改变: 2 个新的 interrupt and dpc 字段被返回在 Windows。
psutil.
cpu_count
(
logical=True
)
¶
返回系统中的 CPU 逻辑数 (如同
os.cpu_count
在 Python 3.4) 或
None
若不确定。逻辑 CPU 意味着物理核心数乘以每个核心可以运行的线程数 (这被称为超线程)。若
logical
is
False
只返回物理核心数,或
None
若不确定。在 OpenBSD 和 NetBSD
psutil.cpu_count(logical=False)
始终返回
None
。系统拥有 2 核心 + 超线程的范例:
>>> import psutil >>> psutil.cpu_count() 4 >>> psutil.cpu_count(logical=False) 2
注意,
psutil.cpu_count()
可能不一定相当于当前进程可以使用的实际 CPU 数。这会有所不同若进程 CPU 倾向性改变,当正使用 Linux cgroups 或 (对于 Windows) 当系统使用处理器组或拥有 64 个以上 CPU 时。可用 CPU 数可以获得采用:
>>> len(psutil.Process().cpu_affinity()) 1
psutil.
cpu_stats
(
)
¶
以命名元组形式返回各种 CPU 统计信息:
0
在 Windows 和 SunOS。
0
在 Linux。
范例 (Linux):
>>> import psutil >>> psutil.cpu_stats() scpustats(ctx_switches=20455687, interrupts=6598984, soft_interrupts=2134212, syscalls=0)
4.1.0 版新增。
psutil.
cpu_freq
(
percpu=False
)
¶
以命名元组形式返回 CPU 频率包括
current
,
min
and
max
频率以 Mhz 为单位表达。在 Linux
current
频率报告实时值,在所有其它平台,这通常表示名义 "固定" 值 (从不改变)。若
percpu
is
True
且系统支持每 CPU 频率检索 (仅 Linux) 各 CPU 返回的频率列表,若不支持,返回具有单元素的列表。若
min
and
max
无法确定,它们被设为
0.0
.
范例 (Linux):
>>> import psutil >>> psutil.cpu_freq() scpufreq(current=931.42925, min=800.0, max=3500.0) >>> psutil.cpu_freq(percpu=True) [scpufreq(current=2394.945, min=800.0, max=3500.0), scpufreq(current=2236.812, min=800.0, max=3500.0), scpufreq(current=1703.609, min=800.0, max=3500.0), scpufreq(current=1754.289, min=800.0, max=3500.0)]
可用性: Linux、macOS、Windows、FreeBSD、OpenBSD
5.1.0 版新增。
5.5.1 版改变: 添加 FreeBSD 支持。
5.9.1 版改变: 添加 OpenBSD 支持。
psutil.
getloadavg
(
)
¶
以元组形式返回最后 1 分钟、5 分钟及 15 分钟内的平均系统负载。"负载" 表示处于可运行状态下的进程,正使用 CPU,或正等待使用 CPU (如:等待磁盘 I/O)。在 UNIX 系统,这依赖
os.getloadavg
。在 Windows,这的模拟是通过使用 Windows API 卵生在后台保持运行的线程,模仿 UNIX 行为每 5 秒更新一次结果。因此,在 Windows,首次调用和在接下来的 5 秒内,它将返回无意义
(0.0, 0.0, 0.0)
元组。返回的数字才有意义当与系统安装的 CPU 核心数相关时。所以,例如值
3.14
在具有 10 个逻辑 CPU 的系统,意味着最后 N 分钟内系统负载为 31.4%。
>>> import psutil >>> psutil.getloadavg() (3.14, 3.89, 4.67) >>> psutil.cpu_count() 10 >>> # percentage representation >>> [x / psutil.cpu_count() * 100 for x in psutil.getloadavg()] [31.4, 38.9, 46.7]
可用性:Unix、Windows
5.6.2 版新增。
psutil.
virtual_memory
(
)
¶
以命名元组形式返回系统内存用量的有关统计信息,以字节为单位表达包括下列字段。主要指标:
其它指标:
和对于 used and available 不必等于 total 。在 Windows available and free 是相同的。见 meminfo.py script providing an example on how to convert bytes in a human readable form.
注意
if you just want to know how much physical memory is left in a cross platform fashion simply rely on the available 字段。
>>> import psutil >>> mem = psutil.virtual_memory() >>> mem svmem(total=10367352832, available=6472179712, percent=37.6, used=8186245120, free=2181107712, active=4748992512, inactive=2758115328, buffers=790724608, cached=3500347392, shared=787554304, slab=199348224) >>> >>> THRESHOLD = 100 * 1024 * 1024 # 100MB >>> if mem.available <= THRESHOLD: ... print("warning") ... >>>
4.2.0 版改变: 添加 shared 指标在 Linux。
5.4.4 版改变: 添加 slab 指标在 Linux。
psutil.
swap_memory
(
)
¶
Return system swap memory statistics as a named tuple including the following fields:
(total - available) / total * 100
sin
and
sout
on Windows are always set to
0
。见
meminfo.py
script providing an example on how to convert bytes in a human readable form.
>>> import psutil >>> psutil.swap_memory() sswap(total=2097147904L, used=886620160L, free=1210527744L, percent=42.3, sin=1050411008, sout=1906720768)
5.2.3 版改变:
on Linux this function relies on /proc fs instead of sysinfo() syscall so that it can be used in conjunction with
psutil.PROCFS_PATH
in order to retrieve memory info about Linux containers such as Docker and Heroku.
psutil.
disk_partitions
(
all=False
)
¶
以命名元组列表形式返回所有挂载的磁盘分区,包括设备、挂载点及文件系统类型,类似 UNIX df 命令。若
all
参数为
False
它会试着区分并返回仅物理设备 (如硬盘、 CD-ROM 驱动器,USB 键),忽略其它所有 (如:伪、内存、重复、不可访问的文件系统)。注意,这在所有系统中可能并非完全可靠 (如:在 BSD 此参数被忽略)。见
disk_usage.py
脚本提供范例用法。返回带以下字段的命名元组列表:
"/dev/hda1"
). On Windows this is the drive letter (e.g.
"C:\\"
).
"/"
). On Windows this is the drive letter (e.g.
"C:\\"
).
"ext3"
on UNIX or
"NTFS"
在 Windows)。
>>> import psutil >>> psutil.disk_partitions() [sdiskpart(device='/dev/sda3', mountpoint='/', fstype='ext4', opts='rw,errors=remount-ro', maxfile=255, maxpath=4096), sdiskpart(device='/dev/sda7', mountpoint='/home', fstype='ext4', opts='rw', maxfile=255, maxpath=4096)]
5.7.4 版改变: 添加 maxfile and maxpath 字段
psutil.
disk_usage
(
path
)
¶
返回磁盘使用统计信息关于分区包含给定
path
以命名元组形式包括
total
,
used
and
free
空间以字节为单位表达,加
percentage
使用率。
OSError
被引发若
path
不存在。从 Python 3.3 起,这也是可用的作为
shutil.disk_usage
(见
BPO-12442
)。见
disk_usage.py
脚本提供的范例用法。
>>> import psutil >>> psutil.disk_usage('/') sdiskusage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)
注意
UNIX 通常为 root 用户预留总磁盘空间的 5%。 total and used 字段在 UNIX 是指整体总计的已用空间,而 free 表示可用空间对于 user and percent 表示 user 利用率 (见 源代码 )。这是为什么 percent 值看起来可能比期望值高出 5%。另注意,这 4 个值都匹配 df 命令行实用程序。
4.3.0 版改变: percent 值考虑了 root 预留空间。
psutil.
disk_io_counters
(
perdisk=False
,
nowrap=True
)
¶
以命名元组形式返回系统范围磁盘 I/O 统计信息,包括下列字段:
特定平台字段:
若
perdisk
is
True
return the same information for every physical disk installed on the system as a dictionary with partition names as the keys and the named tuple described above as the values. See
iotop.py
for an example application. On some systems such as Linux, on a very busy or long-lived system, the numbers returned by the kernel may overflow and wrap (restart from zero). If
nowrap
is
True
psutil will detect and adjust those numbers across function calls and add “old value” to “new value” so that the returned numbers will always be increasing or remain the same, but never decrease.
disk_io_counters.cache_clear()
can be used to invalidate the
nowrap
cache. On Windows it may be ncessary to issue
diskperf -y
command from cmd.exe first in order to enable IO counters. On diskless machines this function will return
None
or
{}
if
perdisk
is
True
.
>>> import psutil >>> psutil.disk_io_counters() sdiskio(read_count=8141, write_count=2431, read_bytes=290203, write_bytes=537676, read_time=5868, write_time=94922) >>> >>> psutil.disk_io_counters(perdisk=True) {'sda1': sdiskio(read_count=920, write_count=1, read_bytes=2933248, write_bytes=512, read_time=6016, write_time=4), 'sda2': sdiskio(read_count=18707, write_count=8830, read_bytes=6060, write_bytes=3443, read_time=24585, write_time=1572), 'sdb1': sdiskio(read_count=161, write_count=0, read_bytes=786432, write_bytes=0, read_time=44, write_time=0)}
注意
在 Windows
"diskperf -y"
command may need to be executed first otherwise this function won’t find any disk.
5.3.0 版改变: numbers no longer wrap (restart from zero) across calls thanks to new nowrap 自变量。
4.0.0 版改变: 添加 busy_time (Linux, FreeBSD), read_merged_count and write_merged_count (Linux) fields.
4.0.0 版改变: NetBSD 不再拥有 read_time and write_time 字段。
psutil.
net_io_counters
(
pernic=False
,
nowrap=True
)
¶
以命名元组形式返回系统范围网络 IO 统计信息,包括下列属性:
若
pernic
is
True
return the same information for every network interface installed on the system as a dictionary with network interface names as the keys and the named tuple described above as the values. On some systems such as Linux, on a very busy or long-lived system, the numbers returned by the kernel may overflow and wrap (restart from zero). If
nowrap
is
True
psutil will detect and adjust those numbers across function calls and add “old value” to “new value” so that the returned numbers will always be increasing or remain the same, but never decrease.
net_io_counters.cache_clear()
can be used to invalidate the
nowrap
cache. On machines with no network interfaces this function will return
None
or
{}
if
pernic
is
True
.
>>> import psutil >>> psutil.net_io_counters() snetio(bytes_sent=14508483, bytes_recv=62749361, packets_sent=84311, packets_recv=94888, errin=0, errout=0, dropin=0, dropout=0) >>> >>> psutil.net_io_counters(pernic=True) {'lo': snetio(bytes_sent=547971, bytes_recv=547971, packets_sent=5075, packets_recv=5075, errin=0, errout=0, dropin=0, dropout=0), 'wlan0': snetio(bytes_sent=13921765, bytes_recv=62162574, packets_sent=79097, packets_recv=89648, errin=0, errout=0, dropin=0, dropout=0)}
另请参阅 nettop.py and ifconfig.py 了解范例应用程序。
5.3.0 版改变: numbers no longer wrap (restart from zero) across calls thanks to new nowrap 自变量。
psutil.
net_connections
(
kind='inet'
)
¶
Return system-wide socket connections as a list of named tuples. Every named tuple provides 7 attributes:
-1
.
(ip, port)
命名元组或
path
in case of AF_UNIX sockets. For UNIX sockets see notes below.
(ip, port)
named tuple or an absolute
path
in case of UNIX sockets. When the remote endpoint is not connected you’ll get an empty tuple (AF_INET*) or
""
(AF_UNIX). For UNIX sockets see notes below.
psutil.CONN_NONE
.
None
. On some platforms (e.g. Linux) the availability of this field changes depending on process privileges (root is needed).
The kind parameter is a string which filters for connections matching the following criteria:
| 种类值 | 连接使用 |
|---|---|
"inet"
|
IPv4 和 IPv6 |
"inet4"
|
IPv4 |
"inet6"
|
IPv6 |
"tcp"
|
TCP |
"tcp4"
|
TCP over IPv4 |
"tcp6"
|
TCP over IPv6 |
"udp"
|
UDP |
"udp4"
|
UDP over IPv4 |
"udp6"
|
UDP over IPv6 |
"unix"
|
UNIX 套接字 (UDP 和 TCP 协议) |
"all"
|
所有可能系列和协议的和 |
On macOS and AIX this function requires root privileges. To get per-process connections use
Process.connections()
. Also, see
netstat.py
example script. Example:
>>> import psutil >>> psutil.net_connections() [pconn(fd=115, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=48776), raddr=addr(ip='93.186.135.91', port=80), status='ESTABLISHED', pid=1254), pconn(fd=117, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=43761), raddr=addr(ip='72.14.234.100', port=80), status='CLOSING', pid=2987), pconn(fd=-1, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=60759), raddr=addr(ip='72.14.234.104', port=80), status='ESTABLISHED', pid=None), pconn(fd=-1, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=51314), raddr=addr(ip='72.14.234.83', port=443), status='SYN_SENT', pid=None) ...]
注意
(macOS and AIX)
psutil.AccessDenied
is always raised unless running as root. This is a limitation of the OS and
lsof
does the same.
注意
(Solaris) 不支持 UNIX 套接字。
注意
(Linux, FreeBSD) “raddr” field for UNIX sockets is always set to “”. This is a limitation of the OS.
注意
(OpenBSD) “laddr” and “raddr” fields for UNIX sockets are always set to “”. This is a limitation of the OS.
2.1.0 版新增。
5.3.0 版改变:
: socket “fd” is now set for real instead of being
-1
.
5.3.0 版改变: :laddr 和 raddr 是命名元组。
psutil.
net_if_addrs
(
)
¶
Return the addresses associated to each NIC (network interface card) installed on the system as a dictionary whose keys are the NIC names and value is a list of named tuples for each address assigned to the NIC. Each named tuple includes 5 fields:
psutil.AF_LINK
,其引用 MAC 地址。
None
).
None
).
None
.
范例:
>>> import psutil >>> psutil.net_if_addrs() {'lo': [snicaddr(family=<AddressFamily.AF_INET: 2>, address='127.0.0.1', netmask='255.0.0.0', broadcast='127.0.0.1', ptp=None), snicaddr(family=<AddressFamily.AF_INET6: 10>, address='::1', netmask='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None, ptp=None), snicaddr(family=<AddressFamily.AF_LINK: 17>, address='00:00:00:00:00:00', netmask=None, broadcast='00:00:00:00:00:00', ptp=None)], 'wlan0': [snicaddr(family=<AddressFamily.AF_INET: 2>, address='192.168.1.3', netmask='255.255.255.0', broadcast='192.168.1.255', ptp=None), snicaddr(family=<AddressFamily.AF_INET6: 10>, address='fe80::c685:8ff:fe45:641%wlan0', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None), snicaddr(family=<AddressFamily.AF_LINK: 17>, address='c4:85:08:45:06:41', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)]} >>>
另请参阅 nettop.py and ifconfig.py 了解范例应用程序。
注意
if you’re interested in others families (e.g. AF_BLUETOOTH) you can use the more powerful netifaces extension.
注意
you can have more than one address of the same family associated with each interface (that’s why dict values are lists).
注意
broadcast
and
ptp
are not supported on Windows and are always
None
.
3.0.0 版新增。
3.2.0 版改变: ptp 字段被添加。
4.4.0 版改变:
添加支持
netmask
field on Windows which is no longer
None
.
psutil.
net_if_stats
(
)
¶
Return information about each NIC (network interface card) installed on the system as a dictionary whose keys are the NIC names and value is a named tuple with the following fields:
isup : a bool indicating whether the NIC is up and running (meaning ethernet cable or Wi-Fi is connected).
duplex
: the duplex communication type; it can be either
NIC_DUPLEX_FULL
,
NIC_DUPLEX_HALF
or
NIC_DUPLEX_UNKNOWN
.
speed
: the NIC speed expressed in mega bits (MB), if it can’t be determined (e.g. ‘localhost’) it will be set to
0
.
mtu : NIC’s maximum transmission unit expressed in bytes.
flags
: a string of comma-separated flags on the interface (may be an empty string). Possible flags are:
up
,
broadcast
,
debug
,
loopback
,
pointopoint
,
notrailers
,
running
,
noarp
,
promisc
,
allmulti
,
master
,
slave
,
multicast
,
portsel
,
dynamic
,
oactive
,
simplex
,
link0
,
link1
,
link2
,和
d2
(some flags are only available on certain platforms).
可用性:Unix
范例:
>>> import psutil >>> psutil.net_if_stats() {'eth0': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=100, mtu=1500, flags='up,broadcast,running,multicast'), 'lo': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_UNKNOWN: 0>, speed=0, mtu=65536, flags='up,loopback,running')}
另请参阅 nettop.py and ifconfig.py 了解范例应用程序。
3.0.0 版新增。
5.7.3 版改变: isup 在 UNIX 还校验 NIC (网卡) 是否运行。
5.9.3 版改变: flags 字段被添加在 POSIX。
psutil.
sensors_temperatures
(
fahrenheit=False
)
¶
返回硬件温度。每个条目都是表示某个硬件温度传感器 (可能是 CPU、硬盘或其它东西,从属操作系统及其配置) 的命名元组。以摄氏为单位表示所有温度,除非
fahrenheit
被设为
True
。若 OS 不支持传感器,返回空字典。范例:
>>> import psutil >>> psutil.sensors_temperatures() {'acpitz': [shwtemp(label='', current=47.0, high=103.0, critical=103.0)], 'asus': [shwtemp(label='', current=47.0, high=None, critical=None)], 'coretemp': [shwtemp(label='Physical id 0', current=52.0, high=100.0, critical=100.0), shwtemp(label='Core 0', current=45.0, high=100.0, critical=100.0), shwtemp(label='Core 1', current=52.0, high=100.0, critical=100.0), shwtemp(label='Core 2', current=45.0, high=100.0, critical=100.0), shwtemp(label='Core 3', current=47.0, high=100.0, critical=100.0)]}
另请参阅 temperatures.py and sensors.py 了解范例应用程序。
可用性:Linux、FreeBSD
5.1.0 版新增。
5.5.0 版改变: 添加 FreeBSD 支持
psutil.
sensors_fans
(
)
¶
返回硬件风扇速度。每个条目都是表示某个硬件传感器风扇的命名元组。风扇速度以 RPM (转每分钟) 为单位表达。若 OS 不支持传感器,返回空字典。范例:
>>> import psutil >>> psutil.sensors_fans() {'asus': [sfan(label='cpu_fan', current=3200)]}
另请参阅 fans.py and sensors.py 了解范例应用程序。
可用性:Linux
5.2.0 版新增。
psutil.
sensors_battery
(
)
¶
以命名元组形式返回电池状态信息,包括下列值。若未安装电池或无法确定指标
None
被返回。
psutil.POWER_TIME_UNLIMITED
. If it can’t be determined it is set to
psutil.POWER_TIME_UNKNOWN
.
True
若连接的是 AC (交流) 电源线,
False
if not or
None
if it can’t be determined.
范例:
>>> import psutil >>> >>> def secs2hours(secs): ... mm, ss = divmod(secs, 60) ... hh, mm = divmod(mm, 60) ... return "%d:%02d:%02d" % (hh, mm, ss) ... >>> battery = psutil.sensors_battery() >>> battery sbattery(percent=93, secsleft=16628, power_plugged=False) >>> print("charge = %s%%, time left = %s" % (battery.percent, secs2hours(battery.secsleft))) charge = 93%, time left = 4:37:08
另请参阅 battery.py and sensors.py 了解范例应用程序。
可用性:Linux、Windows、FreeBSD
5.1.0 版新增。
5.4.2 版改变: 添加 macOS 支持
psutil.
boot_time
(
)
¶
返回以秒为单位表达,自纪元起的系统引导时间。范例:
>>> import psutil, datetime >>> psutil.boot_time() 1389563460.0 >>> datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S") '2014-01-12 22:51:00'
注意
on Windows this function may return a time which is off by 1 second if it’s used across different processes (see issue #1007 ).
psutil.
users
(
)
¶
Return users currently connected on the system as a list of named tuples including the following fields:
None
.
None
.
范例:
>>> import psutil >>> psutil.users() [suser(name='giampaolo', terminal='pts/2', host='localhost', started=1340737536.0, pid=1352), suser(name='giampaolo', terminal='pts/3', host='localhost', started=1340737792.0, pid=1788)]
5.3.0 版改变: 添加 pid 字段
psutil.
pids
(
)
¶
返回当前运行 PID 的排序列表。要遍历所有进程和避免竞争条件
process_iter()
应该是首选的。
>>> import psutil >>> psutil.pids() [1, 2, 3, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, ..., 32498]
5.6.0 版改变: PID 按排序次序返回
psutil.
process_iter
(
attrs=None
,
ad_value=None
)
¶
返回迭代器产生
Process
类实例,为本地机器中正运行的所有进程。应首选这相比
psutil.pids()
来迭代进程,因为它对竞态条件来说是安全的。
每个
Process
实例只创建一次,然后缓存用于下次
psutil.process_iter()
被调用 (若 PID 仍存活)。此外,它还确保进程 PID 不被重用。
attrs
and
ad_value
拥有相同含义如在
Process.as_dict()
。若
attrs
有指定
Process.as_dict()
结果将存储为
info
属性被附加到返回的
Process
实例。若
attrs
是将检索所有进程信息 (慢) 的空列表。
进程返回的排序次序,是基于其 PID。
范例:
>>> import psutil >>> for proc in psutil.process_iter(['pid', 'name', 'username']): ... print(proc.info) ... {'name': 'systemd', 'pid': 1, 'username': 'root'} {'name': 'kthreadd', 'pid': 2, 'username': 'root'} {'name': 'ksoftirqd/0', 'pid': 3, 'username': 'root'} ...
字典推导能创建
{pid: info, ...}
数据结构:
>>> import psutil >>> procs = {p.pid: p.info for p in psutil.process_iter(['name', 'username'])} >>> procs {1: {'name': 'systemd', 'username': 'root'}, 2: {'name': 'kthreadd', 'username': 'root'}, 3: {'name': 'ksoftirqd/0', 'username': 'root'}, ...}
5.3.0 版改变: 添加 attrs 和 ad_value 参数。
psutil.
pid_exists
(
pid
)
¶
校验给定 PID 是否存在于当前进程列表中。这更快相比履行
pid in psutil.pids()
且应该是首选的。
psutil.
wait_procs
(
procs
,
timeout=None
,
callback=None
)
¶
方便函数等待列表
Process
实例终止。返回
(gone, alive)
元组指示哪些进程已离去,哪些进程仍存活。
gone
的将有新的
returncode
属性指示进程退出状态如返回通过
Process.wait()
.
callback
是被调用函数,当某个在等待进程终止且
Process
实例被传递作为回调自变量 (实例也将拥有
returncode
属性设置)。此函数将返回一旦所有进程终止,或者当
timeout
(秒) 出现。异于
Process.wait()
它不会引发
TimeoutExpired
若出现超时。典型用例可能是:
终止并等待此进程的所有子级的范例:
import psutil def on_terminate(proc): print("process {} terminated with exit code {}".format(proc, proc.returncode)) procs = psutil.Process().children() for p in procs: p.terminate() gone, alive = psutil.wait_procs(procs, timeout=3, callback=on_terminate) for p in alive: p.kill()
psutil.
Error
¶
基异常类。所有其它异常都继承自此异常。
psutil.
NoSuchProcess
(
pid
,
name=None
,
msg=None
)
¶
被引发通过
Process
类方法当没有进程具有给定
pid
在当前进程列表中被找到,或者当进程不再存在时。
name
是进程在消失之前的名称且才获取设置若
Process.name()
先前有调用。
psutil.
ZombieProcess
(
pid
,
name=None
,
ppid=None
,
msg=None
)
¶
这可能被引发通过
Process
类方法,当在 UNIX 查询僵尸进程时 (Windows 没有僵尸进程)。
name
and
ppid
属性是可用的若
Process.name()
or
Process.ppid()
方法被调用,在进程变成僵尸之前。
注意
这是子类化的
NoSuchProcess
所以若对检索僵尸不感兴趣 (如:当使用
process_iter()
) 可以忽略此异常且仅仅捕获
NoSuchProcess
.
3.0.0 版新增。
psutil.
AccessDenied
(
pid=None
,
name=None
,
msg=None
)
¶
被引发通过
Process
类方法当履行动作的权限被拒绝时,由于权限不足。
name
属性是可用的若
Process.name()
先前有调用。
psutil.
TimeoutExpired
(
seconds
,
pid=None
,
name=None
,
msg=None
)
¶
被引发通过
Process.wait()
方法若超时过期,且进程仍存活。
name
属性是可用的若
Process.name()
先前有调用。
psutil.
Process
(
pid=None
)
¶
表示 OS 进程具有给定
pid
。若
pid
被省略,当前进程
pid
(
os.getpid
) 被使用。引发
NoSuchProcess
if
pid
不存在。在 Linux
pid
还可以指线程 ID (
id
字段返回通过
threads()
方法)。当访问此类的方法始终准备捕获
NoSuchProcess
and
AccessDenied
异常。
hash
内置可以用于此类的实例,随着时间的推移无歧义标识进程 (哈希由进程 PID + 创建时间混合确定)。因此,还可以用于
set
.
注意
为同时高效抓取有关进程的多条信息,确保使用
oneshot()
上下文管理器或
as_dict()
实用方法。
注意
此类绑定进程的方式是唯一的,凭借其
PID
。这意味着若进程终止且 OS 重用其 PID,最终可能与另一进程进行交互。优先校验进程标识 (凭借 PID + 创建时间) 的唯一例外是下列方法:
nice()
(set),
ionice()
(set),
cpu_affinity()
(set),
rlimit()
(set),
children()
,
parent()
,
parents()
,
suspend()
resume()
,
send_signal()
,
terminate()
kill()
。为阻止所有其它方法的这种问题,可以使用
is_running()
先于查询进程或
process_iter()
若正遍历所有进程。必须注意,除非处理非常 "老" 的 (不活动)
Process
实例,这几乎不构成问题。
oneshot
(
)
¶
可大大加速同时检索多个进程信息的实用上下文管理器。内部不同进程信息 (如
name()
,
ppid()
,
uids()
,
create_time()
, …) may be fetched by using the same routine, but only one value is returned and the others are discarded. When using this context manager the internal routine is executed once (in the example below on
name()
) the value of interest is returned and the others are cached. The subsequent calls sharing the same internal routine will return the cached value. The cache is cleared when exiting the context manager block. The advice is to use this every time you retrieve more than one information about the process. If you’re lucky, you’ll get a hell of a speedup. Example:
>>> import psutil >>> p = psutil.Process() >>> with p.oneshot(): ... p.name() # execute internal routine once collecting multiple info ... p.cpu_times() # return cached value ... p.cpu_percent() # return cached value ... p.create_time() # return cached value ... p.ppid() # return cached value ... p.status() # return cached value ... >>>
Here’s a list of methods which can take advantage of the speedup depending on what platform you’re on. In the table below horizontal empty rows indicate what process methods can be efficiently grouped together internally. The last column (speedup) shows an approximation of the speedup you can get if you call all the methods together (best case scenario).
5.0.0 版新增。
pid
¶
进程 PID。这是类的唯一 (只读) 属性。
ppid
(
)
¶
进程父级 PID。在 Windows,首次调用后缓存返回值。不是在 POSIX,因为 PPID 可能改变若进程变成僵尸,另请参阅
parent()
and
parents()
方法。
exe
(
)
¶
作为绝对路径的进程可执行文件。在某些系统,这还可能是空字符串。会缓存返回值,在首次调用后。
>>> import psutil >>> psutil.Process().exe() '/usr/bin/python2.7'
cmdline
(
)
¶
调用此进程的命令行如采用字符串列表。不缓存返回值,因为进程的命令行可能改变。
>>> import psutil >>> psutil.Process().cmdline() ['python', 'manage.py', 'runserver']
environ
(
)
¶
进程的环境变量如字典。注意:这可能不反映所做的改变,在进程启动之后。
>>> import psutil >>> psutil.Process().environ() {'LC_NUMERIC': 'it_IT.UTF-8', 'QT_QPA_PLATFORMTHEME': 'appmenu-qt5', 'IM_CONFIG_PHASE': '1', 'XDG_GREETER_DATA_DIR': '/var/lib/lightdm-data/giampaolo', 'GNOME_DESKTOP_SESSION_ID': 'this-is-deprecated', 'XDG_CURRENT_DESKTOP': 'Unity', 'UPSTART_EVENTS': 'started starting', 'GNOME_KEYRING_PID': '', 'XDG_VTNR': '7', 'QT_IM_MODULE': 'ibus', 'LOGNAME': 'giampaolo', 'USER': 'giampaolo', 'PATH': '/home/giampaolo/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/home/giampaolo/svn/sysconf/bin', 'LC_PAPER': 'it_IT.UTF-8', 'GNOME_KEYRING_CONTROL': '', 'GTK_IM_MODULE': 'ibus', 'DISPLAY': ':0', 'LANG': 'en_US.UTF-8', 'LESS_TERMCAP_se': '\x1b[0m', 'TERM': 'xterm-256color', 'SHELL': '/bin/bash', 'XDG_SESSION_PATH': '/org/freedesktop/DisplayManager/Session0', 'XAUTHORITY': '/home/giampaolo/.Xauthority', 'LANGUAGE': 'en_US', 'COMPIZ_CONFIG_PROFILE': 'ubuntu', 'LC_MONETARY': 'it_IT.UTF-8', 'QT_LINUX_ACCESSIBILITY_ALWAYS_ON': '1', 'LESS_TERMCAP_me': '\x1b[0m', 'LESS_TERMCAP_md': '\x1b[01;38;5;74m', 'LESS_TERMCAP_mb': '\x1b[01;31m', 'HISTSIZE': '100000', 'UPSTART_INSTANCE': '', 'CLUTTER_IM_MODULE': 'xim', 'WINDOWID': '58786407', 'EDITOR': 'vim', 'SESSIONTYPE': 'gnome-session', 'XMODIFIERS': '@im=ibus', 'GPG_AGENT_INFO': '/home/giampaolo/.gnupg/S.gpg-agent:0:1', 'HOME': '/home/giampaolo', 'HISTFILESIZE': '100000', 'QT4_IM_MODULE': 'xim', 'GTK2_MODULES': 'overlay-scrollbar', 'XDG_SESSION_DESKTOP': 'ubuntu', 'SHLVL': '1', 'XDG_RUNTIME_DIR': '/run/user/1000', 'INSTANCE': 'Unity', 'LC_ADDRESS': 'it_IT.UTF-8', 'SSH_AUTH_SOCK': '/run/user/1000/keyring/ssh', 'VTE_VERSION': '4205', 'GDMSESSION': 'ubuntu', 'MANDATORY_PATH': '/usr/share/gconf/ubuntu.mandatory.path', 'VISUAL': 'vim', 'DESKTOP_SESSION': 'ubuntu', 'QT_ACCESSIBILITY': '1', 'XDG_SEAT_PATH': '/org/freedesktop/DisplayManager/Seat0', 'LESSCLOSE': '/usr/bin/lesspipe %s %s', 'LESSOPEN': '| /usr/bin/lesspipe %s', 'XDG_SESSION_ID': 'c2', 'DBUS_SESSION_BUS_ADDRESS': 'unix:abstract=/tmp/dbus-9GAJpvnt8r', '_': '/usr/bin/python', 'DEFAULTS_PATH': '/usr/share/gconf/ubuntu.default.path', 'LC_IDENTIFICATION': 'it_IT.UTF-8', 'LESS_TERMCAP_ue': '\x1b[0m', 'UPSTART_SESSION': 'unix:abstract=/com/ubuntu/upstart-session/1000/1294', 'XDG_CONFIG_DIRS': '/etc/xdg/xdg-ubuntu:/usr/share/upstart/xdg:/etc/xdg', 'GTK_MODULES': 'gail:atk-bridge:unity-gtk-module', 'XDG_SESSION_TYPE': 'x11', 'PYTHONSTARTUP': '/home/giampaolo/.pythonstart', 'LC_NAME': 'it_IT.UTF-8', 'OLDPWD': '/home/giampaolo/svn/curio_giampaolo/tests', 'GDM_LANG': 'en_US', 'LC_TELEPHONE': 'it_IT.UTF-8', 'HISTCONTROL': 'ignoredups:erasedups', 'LC_MEASUREMENT': 'it_IT.UTF-8', 'PWD': '/home/giampaolo/svn/curio_giampaolo', 'JOB': 'gnome-session', 'LESS_TERMCAP_us': '\x1b[04;38;5;146m', 'UPSTART_JOB': 'unity-settings-daemon', 'LC_TIME': 'it_IT.UTF-8', 'LESS_TERMCAP_so': '\x1b[38;5;246m', 'PAGER': 'less', 'XDG_DATA_DIRS': '/usr/share/ubuntu:/usr/share/gnome:/usr/local/share/:/usr/share/:/var/lib/snapd/desktop', 'XDG_SEAT': 'seat0'}
注意
在 macOS Big Sur,此函数返回的内容仅对当前进程有意义,或在 其它特定情况 ).
4.0.0 版新增。
5.3.0 版改变: 添加 SunOS 支持
5.6.3 版改变: 添加 AIX 支持
5.7.3 版改变: 添加 BSD 支持
create_time
(
)
¶
进程创建时间以浮点数形式表达,从纪元起以秒为单位。首次调用后缓存返回值。
>>> import psutil, datetime >>> p = psutil.Process() >>> p.create_time() 1307289803.47 >>> datetime.datetime.fromtimestamp(p.create_time()).strftime("%Y-%m-%d %H:%M:%S") '2011-03-05 18:03:52'
as_dict
(
attrs=None
,
ad_value=None
)
¶
以字典形式检索多个进程信息的实用方法。若
attrs
有指定,它必须是字符串列表反映可用
Process
类的属性名。这里是可能的字符串值列表:
'cmdline'
,
'connections'
,
'cpu_affinity'
,
'cpu_num'
,
'cpu_percent'
,
'cpu_times'
,
'create_time'
,
'cwd'
,
'environ'
,
'exe'
,
'gids'
,
'io_counters'
,
'ionice'
,
'memory_full_info'
,
'memory_info'
,
'memory_maps'
,
'memory_percent'
,
'name'
,
'nice'
,
'num_ctx_switches'
,
'num_fds'
,
'num_handles'
,
'num_threads'
,
'open_files'
,
'pid'
,
'ppid'
,
'status'
,
'terminal'
,
'threads'
,
'uids'
,
'username'`
。若
attrs
自变量不传递所有公共只读假定属性。
ad_value
是赋值给字典键的值若
AccessDenied
or
ZombieProcess
异常被引发当检索特定进程信息时。在内部,
as_dict()
使用
oneshot()
上下文管理器,所以也不需要使用它。
>>> import psutil >>> p = psutil.Process() >>> p.as_dict(attrs=['pid', 'name', 'username']) {'username': 'giampaolo', 'pid': 12366, 'name': 'python'} >>> >>> # get a list of valid attrs names >>> list(psutil.Process().as_dict().keys()) ['status', 'cpu_num', 'num_ctx_switches', 'pid', 'memory_full_info', 'connections', 'cmdline', 'create_time', 'ionice', 'num_fds', 'memory_maps', 'cpu_percent', 'terminal', 'ppid', 'cwd', 'nice', 'username', 'cpu_times', 'io_counters', 'memory_info', 'threads', 'open_files', 'name', 'num_threads', 'exe', 'uids', 'gids', 'cpu_affinity', 'memory_percent', 'environ']
3.0.0 版改变:
ad_value
也被使用当招致
ZombieProcess
异常,不只
AccessDenied
parent
(
)
¶
实用方法返回父级进程以
Process
object, preemptively checking whether PID has been reused. If no parent PID is known return
None
。另请参阅
ppid()
and
parents()
方法。
parents
(
)
¶
实用方法返回此进程的父级以列表化的
Process
instances. If no parents are known return an empty list. See also
ppid()
and
parent()
方法。
5.6.0 版新增。
status
(
)
¶
以字符串形式表示当前进程状态。返回字符串是某一 psutil.STATUS_* 常量。
cwd
(
)
¶
进程当前工作目录如绝对路径。
5.6.4 版改变: 添加支持 NetBSD
username
(
)
¶
拥有进程的用户名。在 UNIX,是通过使用真实进程 uid 计算这。
uids
(
)
¶
以命名元组形式表示此进程的真实、有效和保存的用户 id。这如同 os.getresuid but can be used for any process PID.
可用性:Unix
gids
(
)
¶
以命名元组形式表示此进程的真实、有效和保存的组 id。这如同 os.getresgid but can be used for any process PID.
可用性:Unix
terminal
(
)
¶
关联此进程的终端,若有的话,否则
None
。这类似于 tty 命令,但可以用于任何进程 PID。
可用性:Unix
nice
(
value=None
)
¶
获取 (或设置) 进程好感度 (优先级)。在 UNIX,此数字通常是从
-20
to
20
. The higher the nice value, the lower the priority of the process.
>>> import psutil >>> p = psutil.Process() >>> p.nice(10) # set >>> p.nice() # get 10 >>>
Starting from Python 3.3 this functionality is also available as
os.getpriority
and
os.setpriority
(见
BPO-10784
). On Windows this is implemented via
GetPriorityClass
and
SetPriorityClass
Windows APIs and
value
is one of the
psutil.*_PRIORITY_CLASS
constants reflecting the MSDN documentation. Example which increases process priority on Windows:
>>> p.nice(psutil.HIGH_PRIORITY_CLASS)
ionice
(
ioclass=None
,
value=None
)
¶
获取 (或设置) 进程 I/O 好感度 (优先级)。若不提供自变量则充当获取,返回
(ioclass, value)
tuple on Linux and a
ioclass
integer on Windows. If
ioclass
is provided it acts as a set. In this case an additional
value
can be specified on Linux only in order to increase or decrease the I/O priority even further. Here’s the possible platform-dependent
ioclass
值。
Linux (见 ioprio_get 手册):
IOPRIO_CLASS_RT
: (high) the process gets first access to the disk every time. Use it with care as it can starve the entire system. Additional priority
level
can be specified and ranges from
0
(highest) to
7
(lowest).
IOPRIO_CLASS_BE
: (normal) the default for any process that hasn’t set a specific I/O priority. Additional priority
level
ranges from
0
(highest) to
7
(lowest).
IOPRIO_CLASS_IDLE
: (low) get I/O time when no-one else needs the disk. No additional
value
is accepted.
IOPRIO_CLASS_NONE
: returned when no priority was previously set.
Windows:
IOPRIO_HIGH
:最高优先级。
IOPRIO_NORMAL
:默认优先级。
IOPRIO_LOW
:低优先级。
IOPRIO_VERYLOW
:最低优先级。
这里是关于如何根据是什么平台设置最高 I/O 优先级的范例:
>>> import psutil >>> p = psutil.Process() >>> if psutil.LINUX: ... p.ionice(psutil.IOPRIO_CLASS_RT, value=7) ... else: ... p.ionice(psutil.IOPRIO_HIGH) ... >>> p.ionice() # get pionice(ioclass=<IOPriority.IOPRIO_CLASS_RT: 1>, value=7)
可用性:Linux、Windows Vista+
5.6.2 版改变:
Windows 接受新
IOPRIO_*
常量包括新
IOPRIO_HIGH
.
rlimit
(
resource
,
limits=None
)
¶
获取 (或设置) 进程资源限制 (见
man prlimit
).
resource
is one of the
psutil.RLIMIT_*
常量。
limits
是
(soft, hard)
tuple. This is the same as
resource.getrlimit
and
resource.setrlimit
but can be used for any process PID, not only
os.getpid
. For get, return value is a
(soft, hard)
tuple. Each value may be either and integer or
psutil.RLIMIT_*
。范例:
>>> import psutil >>> p = psutil.Process() >>> p.rlimit(psutil.RLIMIT_NOFILE, (128, 128)) # process can open max 128 file descriptors >>> p.rlimit(psutil.RLIMIT_FSIZE, (1024, 1024)) # can create files no bigger than 1024 bytes >>> p.rlimit(psutil.RLIMIT_FSIZE) # get (1024, 1024) >>>
另请参阅 procinfo.py 脚本。
可用性:Linux、FreeBSD
5.7.3 版改变: 添加 FreeBSD 支持
io_counters
(
)
¶
Return process I/O statistics as a named tuple. For Linux you can refer to /proc 文件系统文档编制 .
read()
and
pread()
on UNIX.
write()
and
pwrite()
on UNIX.
-1
on BSD.
-1
on BSD.
Linux 特有:
read()
and
pread()
syscalls (cumulative). Differently from
read_bytes
it doesn’t care whether or not actual physical disk I/O occurred.
write()
and
pwrite()
syscalls (cumulative). Differently from
write_bytes
it doesn’t care whether or not actual physical disk I/O occurred.
Windows 特有:
>>> import psutil >>> p = psutil.Process() >>> p.io_counters() pio(read_count=454556, write_count=3456, read_bytes=110592, write_bytes=0, read_chars=769931, write_chars=203)
可用性:Linux、BSD、Windows、AIX
5.2.0 版改变: 添加 read_chars and write_chars on Linux; added other_count and other_bytes 在 Windows。
num_ctx_switches
(
)
¶
The number voluntary and involuntary context switches performed by this process (cumulative).
5.4.1 版改变: 添加 AIX 支持
num_fds
(
)
¶
此进程目前打开的文件描述符数 (非累积)。
可用性:Unix
num_handles
(
)
¶
此进程目前使用的句柄数 (非累积)。
可用性:Windows
num_threads
(
)
¶
此进程目前使用的线程数 (非累积)。
threads
(
)
¶
以命名元组列表形式返回由进程打开的线程。在 OpenBSD,此方法要求 root 权限。
pid
是指当前进程,这匹配
native_id
属性在
threading.Thread
类,且可以用于引用运行在自己的 Python APP 中的单独 Python 线程。
cpu_times
(
)
¶
返回表示累计处理时间的命名元组,以秒为单位 (见 解释 )。这类似于 os.times but can be used for any process PID.
0
on Windows and macOS).
0
on Windows and macOS).
>>> import psutil >>> p = psutil.Process() >>> p.cpu_times() pcputimes(user=0.03, system=0.67, children_user=0.0, children_system=0.0, iowait=0.08) >>> sum(p.cpu_times()[:2]) # cumulative, excluding children and iowait 0.70
4.1.0 版改变: return two extra fields: children_user and children_system .
5.6.4 版改变: 添加 iowait 在 Linux。
cpu_percent
(
interval=None
)
¶
Return a float representing the process CPU utilization as a percentage which can also be
> 100.0
in case of a process running multiple threads on different CPUs. When
interval
>
0.0
compares process times to system CPU times elapsed before and after the interval (blocking). When interval is
0.0
or
None
compares process times to system CPU times elapsed since last call, 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 a second time with at least
0.1
seconds between calls. Example:
>>> import psutil >>> p = psutil.Process() >>> # blocking >>> p.cpu_percent(interval=1) 2.0 >>> # non-blocking (percentage since last call) >>> p.cpu_percent(interval=None) 2.9
注意
the returned value can be > 100.0 in case of a process running multiple threads on different CPU cores.
注意
the returned value is explicitly
not
split evenly between all available CPUs (differently from
psutil.cpu_percent()
). This means that a busy loop process running on a system with 2 logical CPUs will be reported as having 100% CPU utilization instead of 50%. This was done in order to be consistent with
top
UNIX utility and also to make it easier to identify processes hogging CPU resources independently from the number of CPUs. It must be noted that
taskmgr.exe
on Windows does not behave like this (it would report 50% usage instead). To emulate Windows
taskmgr.exe
behavior you can do:
p.cpu_percent() / psutil.cpu_count()
.
警告
the first time this method is called with interval =
0.0
or
None
它将返回无意义
0.0
值假设要忽略。
cpu_affinity
(
cpus=None
)
¶
获取或设置进程的当前
CPU 倾向性
. CPU affinity consists in telling the OS to run a process on a limited set of CPUs only (on Linux cmdline,
taskset
command is typically used). If no argument is passed it returns the current CPU affinity as a list of integers. If passed it must be a list of integers specifying the new CPUs affinity. If an empty list is passed all eligible CPUs are assumed (and set). On some systems such as Linux this may not necessarily mean all available logical CPUs as in
list(range(psutil.cpu_count()))
).
>>> import psutil >>> psutil.cpu_count() 4 >>> p = psutil.Process() >>> # get >>> p.cpu_affinity() [0, 1, 2, 3] >>> # set; from now on, process will run on CPU #0 and #1 only >>> p.cpu_affinity([0, 1]) >>> p.cpu_affinity() [0, 1] >>> # reset affinity against all eligible CPUs >>> p.cpu_affinity([])
可用性:Linux、Windows、FreeBSD
2.2.0 版改变: 添加支持 FreeBSD
5.1.0 版改变: an empty list can be passed to set affinity against all eligible CPUs.
cpu_num
(
)
¶
Return what CPU this process is currently running on. The returned number should be
<=
psutil.cpu_count()
. On FreeBSD certain kernel process may return
-1
. It may be used in conjunction with
psutil.cpu_percent(percpu=True)
to observe the system workload distributed across multiple CPUs as shown by
cpu_distribution.py
范例脚本。
可用性:Linux、FreeBSD、SunOS
5.1.0 版新增。
memory_info
(
)
¶
Return a named tuple with variable fields depending on the platform representing memory information about the process. The “portable” fields available on all platforms are rss and vms . All numbers are expressed in bytes.
| Linux | macOS | BSD | Solaris | AIX | Windows |
|---|---|---|---|---|---|
| rss | rss | rss | rss | rss |
rss (别名化的
wset
)
|
| vms | vms | vms | vms | vms |
vms (别名化的
pagefile
)
|
| shared | pfaults | text | num_page_faults | ||
| text | pageins | data | peak_wset | ||
| lib | stack | wset | |||
| data | peak_paged_pool | ||||
| dirty | paged_pool | ||||
| peak_nonpaged_pool | |||||
| nonpaged_pool | |||||
| pagefile | |||||
| peak_pagefile | |||||
| private |
For on explanation of Windows fields rely on PROCESS_MEMORY_COUNTERS_EX structure doc. Example on Linux:
>>> import psutil >>> p = psutil.Process() >>> p.memory_info() pmem(rss=15491072, vms=84025344, shared=5206016, text=2555904, lib=0, data=9891840, dirty=0)
4.0.0 版改变: 返回多个字段,不只 rss and vms .
memory_info_ex
(
)
¶
如同
memory_info()
(弃用)。
警告
在 4.0.0 版弃用;使用
memory_info()
代替。
memory_full_info
(
)
¶
此方法返回的信息如同
memory_info()
, plus, on some platform (Linux, macOS, Windows), also provides additional metrics (USS, PSS and swap). The additional metrics provide a better representation of “effective” process memory consumption (in case of USS) as explained in detail in this
blog post
. It does so by passing through the whole process address. As such it usually requires higher user privileges than
memory_info()
and is considerably slower. On platforms where extra fields are not implemented this simply returns the same metrics as
memory_info()
.
注意
uss is probably the most representative metric for determining how much memory is actually being used by a process. It represents the amount of memory that would be freed if the process was terminated right now.
范例在 Linux:
>>> import psutil >>> p = psutil.Process() >>> p.memory_full_info() pfullmem(rss=10199040, vms=52133888, shared=3887104, text=2867200, lib=0, data=5967872, dirty=0, uss=6545408, pss=6872064, swap=0) >>>
另请参阅 procsmem.py 了解范例应用程序。
4.0.0 版新增。
memory_percent
(
memtype="rss"
)
¶
Compare process memory to total physical system memory and calculate process memory utilization as a percentage.
memtype
argument is a string that dictates what type of process memory you want to compare against. You can choose between the named tuple field names returned by
memory_info()
and
memory_full_info()
(默认为
"rss"
).
4.0.0 版改变: 添加 memtype 参数。
memory_maps
(
grouped=True
)
¶
Return process’s mapped memory regions as a list of named tuples whose fields are variable depending on the platform. This method is useful to obtain a detailed representation of process memory usage as explained
here
(the most important value is “private” memory). If
grouped
is
True
the mapped regions with the same
path
are grouped together and the different memory fields are summed. If
grouped
is
False
each mapped region is shown as a single entity and the named tuple will also include the mapped region’s address space (
addr
) and permission set (
perms
)。见
pmap.py
了解范例应用程序。
| Linux | Windows | FreeBSD | Solaris |
|---|---|---|---|
| rss | rss | rss | rss |
| size | private | anonymous | |
| pss | ref_count | locked | |
| shared_clean | shadow_count | ||
| shared_dirty | |||
| private_clean | |||
| private_dirty | |||
| referenced | |||
| anonymous | |||
| swap |
>>> import psutil >>> p = psutil.Process() >>> p.memory_maps() [pmmap_grouped(path='/lib/x8664-linux-gnu/libutil-2.15.so', rss=32768, size=2125824, pss=32768, shared_clean=0, shared_dirty=0, private_clean=20480, private_dirty=12288, referenced=32768, anonymous=12288, swap=0), pmmap_grouped(path='/lib/x8664-linux-gnu/libc-2.15.so', rss=3821568, size=3842048, pss=3821568, shared_clean=0, shared_dirty=0, private_clean=0, private_dirty=3821568, referenced=3575808, anonymous=3821568, swap=0), ...]
可用性:Linux、Windows、FreeBSD、SunOS
5.6.0 版改变: 移除 macOS 支持,因为固有的损坏 (见问题 #1291 )
children
(
recursive=False
)
¶
以列表形式返回此进程的子级对于
Process
实例。若 recursive 为
True
return all the parent descendants. Pseudo code example assuming
A == this process
:
A ─┐ │ ├─ B (child) ─┐ │ └─ X (grandchild) ─┐ │ └─ Y (great grandchild) ├─ C (child) └─ D (child) >>> p.children() B, C, D >>> p.children(recursive=True) B, X, Y, C, D
Note that in the example above if process X disappears process Y won’t be returned either as the reference to process A is lost. This concept is well summaried by this unit test 。另请参阅如何 杀除进程树 and 终止子级 .
open_files
(
)
¶
返回由进程打开的常规文件,以包括下列字段的命名元组列表形式:
-1
.
仅 Linux:
mode
自变量。可能值为
'r'
,
'w'
,
'a'
,
'r+'
and
'a+'
. There’s no distinction between files opened in binary or text mode (
"b"
or
"t"
).
>>> import psutil >>> f = open('file.ext', 'w') >>> p = psutil.Process() >>> p.open_files() [popenfile(path='/home/giampaolo/svn/psutil/file.ext', fd=3, position=0, mode='w', flags=32769)]
警告
on Windows this method is not reliable due to some limitations of the underlying Windows API which may hang when retrieving certain file handles. In order to work around that psutil spawns a thread to determine the file handle name and kills it if it’s not responding after 100ms. That implies that this method on Windows is not guaranteed to enumerate all regular file handles (see issue 597 ). Tools like ProcessHacker has the same limitation.
警告
on BSD this method can return files with a null path (“”) due to a kernel bug, hence it’s not reliable (see issue 595 ).
3.1.0 版改变: 不再挂起在 Windows。
4.1.0 版改变: new 位置 , mode and flags 字段在 Linux。
connections
(
kind="inet"
)
¶
Return socket connections opened by process as a list of named tuples. To get system-wide connections use
psutil.net_connections()
. Every named tuple provides 6 attributes:
-1
.
(ip, port)
命名元组或
path
in case of AF_UNIX sockets. For UNIX sockets see notes below.
(ip, port)
named tuple or an absolute
path
in case of UNIX sockets. When the remote endpoint is not connected you’ll get an empty tuple (AF_INET*) or
""
(AF_UNIX). For UNIX sockets see notes below.
psutil.CONN_*
constants. For UDP and UNIX sockets this is always going to be
psutil.CONN_NONE
.
The kind parameter is a string which filters for connections that fit the following criteria:
| 种类值 | 连接使用 |
|---|---|
"inet"
|
IPv4 和 IPv6 |
"inet4"
|
IPv4 |
"inet6"
|
IPv6 |
"tcp"
|
TCP |
"tcp4"
|
TCP over IPv4 |
"tcp6"
|
TCP over IPv6 |
"udp"
|
UDP |
"udp4"
|
UDP over IPv4 |
"udp6"
|
UDP over IPv6 |
"unix"
|
UNIX 套接字 (UDP 和 TCP 协议) |
"all"
|
所有可能系列和协议的和 |
范例:
>>> import psutil >>> p = psutil.Process(1694) >>> p.name() 'firefox' >>> p.connections() [pconn(fd=115, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=48776), raddr=addr(ip='93.186.135.91', port=80), status='ESTABLISHED'), pconn(fd=117, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=43761), raddr=addr(ip='72.14.234.100', port=80), status='CLOSING'), pconn(fd=119, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=60759), raddr=addr(ip='72.14.234.104', port=80), status='ESTABLISHED'), pconn(fd=123, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=51314), raddr=addr(ip='72.14.234.83', port=443), status='SYN_SENT')]
注意
(Solaris) 不支持 UNIX 套接字。
注意
(Linux, FreeBSD) “raddr” field for UNIX sockets is always set to “”. This is a limitation of the OS.
注意
(OpenBSD) “laddr” and “raddr” fields for UNIX sockets are always set to “”. This is a limitation of the OS.
注意
(AIX)
psutil.AccessDenied
始终被引发,除非作为 root 运行 (lsof 也这样做)。
5.3.0 版改变: :laddr 和 raddr 是命名元组。
is_running
(
)
¶
Return whether the current process is running in the current process list. This is reliable also in case the process is gone and its PID reused by another process, therefore it must be preferred over doing
psutil.pid_exists(p.pid)
.
注意
这将返回
True
也若进程是僵尸 (
p.status() == psutil.STATUS_ZOMBIE
).
send_signal
(
signal
)
¶
向进程发送信号 (见
signal module
constants) preemptively checking whether PID has been reused. On UNIX this is the same as
os.kill(pid, sig)
. On Windows only
SIGTERM
,
CTRL_C_EVENT
and
CTRL_BREAK_EVENT
signals are supported and
SIGTERM
is treated as an alias for
kill()
。另请参阅如何
杀除进程树
and
终止子级
.
3.2.0 版改变: 在 Windows,添加支持 CTRL_C_EVENT 和 CTRL_BREAK_EVENT 信号。
suspend
(
)
¶
挂起进程执行采用
SIGSTOP
信号优先校验 PID 是否被重用。在 UNIX,这如同
os.kill(pid, signal.SIGSTOP)
。在 Windows,做到这是通过挂起所有进程线程的执行。
resume
(
)
¶
再继续进程执行采用
SIGCONT
信号优先校验 PID 是否被重用。在 UNIX,这如同
os.kill(pid, signal.SIGCONT)
。在 Windows,做到这是通过再继续所有进程线程的执行。
terminate
(
)
¶
终止进程采用
SIGTERM
信号优先校验 PID 是否被重用。在 UNIX,这如同
os.kill(pid, signal.SIGTERM)
。在 Windows,这是别名化的
kill()
。另请参阅如何
杀除进程树
and
终止子级
.
kill
(
)
¶
杀除当前进程通过使用
SIGKILL
信号优先校验 PID 是否被重用。在 UNIX,这如同
os.kill(pid, signal.SIGKILL)
。在 Windows,做到这是通过使用
TerminateProcess
。另请参阅如何
杀除进程树
and
终止子级
.
wait
(
timeout=None
)
¶
等待进程 PID 终止。UNIX 和 Windows 关于返回值的细节会不同。
On UNIX
: if the process terminated normally, the return value is a positive integer >= 0 indicating the exit code. If the process was terminated by a signal return the negated value of the signal which caused the termination (e.g.
-SIGTERM
). If PID is not a children of
os.getpid
(current process) just wait until the process disappears and return
None
. If PID does not exist return
None
立即。
在 Windows : always return the exit code, which is a positive integer as returned by GetExitCodeProcess .
timeout
is expressed in seconds. If specified and the process is still alive raise
TimeoutExpired
异常。
timeout=0
can be used in non-blocking apps: it will either return immediately or raise
TimeoutExpired
.
The return value is cached. To wait for multiple processes use
psutil.wait_procs()
.
>>> import psutil >>> p = psutil.Process(9891) >>> p.terminate() >>> p.wait() <Negsignal.SIGTERM: -15>
5.7.1 版改变:
返回缓存值 (而不是返回
None
).
5.7.1 版改变: on POSIX, in case of negative signal, return it as a human readable enum .
psutil.
Popen
(
*args
,
**kwargs
)
¶
如同
subprocess.Popen
但此外,它还提供所有
psutil.Process
methods in a single class. For the following methods which are common to both classes, psutil implementation takes precedence:
send_signal()
,
terminate()
,
kill()
. This is done in order to avoid killing another process in case its PID has been reused, fixing
BPO-6973
.
>>> import psutil >>> from subprocess import PIPE >>> >>> p = psutil.Popen(["/usr/bin/python", "-c", "print('hello')"], stdout=PIPE) >>> p.name() 'python' >>> p.username() 'giampaolo' >>> p.communicate() ('hello\n', None) >>> p.wait(timeout=2) 0 >>>
4.4.0 版改变: 添加上下文管理器支持
psutil.
win_service_iter
(
)
¶
返回迭代器产生
WindowsService
类实例为所有 Windows 安装服务。
4.2.0 版新增。
可用性:Windows
psutil.
win_service_get
(
name
)
¶
按名称获取 Windows 服务,返回
WindowsService
实例。引发
psutil.NoSuchProcess
若不存在具有这样名称的服务。
4.2.0 版新增。
可用性:Windows
psutil.
WindowsService
¶
Represents a Windows service with the given
name
. This class is returned by
win_service_iter()
and
win_service_get()
functions and it is not supposed to be instantiated directly.
name
(
)
¶
The service name. This string is how a service is referenced and can be passed to
win_service_get()
to get a new
WindowsService
实例。
display_name
(
)
¶
The service display name. The value is cached when this class is instantiated.
binpath
(
)
¶
The fully qualified path to the service binary/exe file as a string, including command line arguments.
username
(
)
¶
拥有此服务的用户名称。
start_type
(
)
¶
A string which can either be “automatic” , “manual” or “disabled” .
pid
(
)
¶
The process PID, if any, else
None
. This can be passed to
Process
class to control the service’s process.
status
(
)
¶
Service status as a string, which may be either “running” , “paused” , “start_pending” , “pause_pending” , “continue_pending” , “stop_pending” or “stopped” .
description
(
)
¶
服务的长描述。
as_dict
(
)
¶
Utility method retrieving all the information above as a dictionary.
4.2.0 版新增。
可用性:Windows
范例代码:
>>> import psutil >>> list(psutil.win_service_iter()) [<WindowsService(name='AeLookupSvc', display_name='Application Experience') at 38850096>, <WindowsService(name='ALG', display_name='Application Layer Gateway Service') at 38850128>, <WindowsService(name='APNMCP', display_name='Ask Update Service') at 38850160>, <WindowsService(name='AppIDSvc', display_name='Application Identity') at 38850192>, ...] >>> s = psutil.win_service_get('alg') >>> s.as_dict() {'binpath': 'C:\\Windows\\System32\\alg.exe', 'description': 'Provides support for 3rd party protocol plug-ins for Internet Connection Sharing', 'display_name': 'Application Layer Gateway Service', 'name': 'alg', 'pid': None, 'start_type': 'manual', 'status': 'stopped', 'username': 'NT AUTHORITY\\LocalService'}
psutil.
POSIX
¶
psutil.
LINUX
¶
psutil.
WINDOWS
¶
psutil.
MACOS
¶
psutil.
FREEBSD
¶
psutil.
NETBSD
¶
psutil.
OPENBSD
¶
psutil.
BSD
¶
psutil.
SUNOS
¶
psutil.
AIX
¶
bool
constants which define what platform you’re on. E.g. if on Windows,
WINDOWS
常量将为
True
,所有其它将为
False
.
4.0.0 版新增。
5.4.0 版改变: 添加 AIX
psutil.
PROCFS_PATH
¶
The path of the /proc filesystem on Linux, Solaris and AIX (defaults to
"/proc"
). You may want to re-set this constant right after importing psutil in case your /proc filesystem is mounted elsewhere or if you want to retrieve information about Linux containers such as Docker, Heroku or LXC (see
here
for more info). It must be noted that this trick works only for APIs which rely on /proc filesystem (e.g.
memory
APIs and most
Process
class methods).
可用性:Linux、Solaris、AIX
3.2.3 版新增。
3.4.2 版改变: 也可用于 Solaris。
5.4.0 版改变: 也可用于 AIX。
psutil.
STATUS_RUNNING
¶
psutil.
STATUS_SLEEPING
¶
psutil.
STATUS_DISK_SLEEP
¶
psutil.
STATUS_STOPPED
¶
psutil.
STATUS_TRACING_STOP
¶
psutil.
STATUS_ZOMBIE
¶
psutil.
STATUS_DEAD
¶
psutil.
STATUS_WAKE_KILL
¶
psutil.
STATUS_WAKING
¶
psutil.
STATUS_PARKED
(
Linux
)
¶
psutil.
STATUS_IDLE
(
Linux
,
macOS
,
FreeBSD
)
¶
psutil.
STATUS_LOCKED
(
FreeBSD
)
¶
psutil.
STATUS_WAITING
(
FreeBSD
)
¶
psutil.
STATUS_SUSPENDED
(
NetBSD
)
¶
表示进程状态。返回通过
psutil.Process.status()
.
3.4.1 版新增:
STATUS_SUSPENDED
(NetBSD)
5.4.7 版新增:
STATUS_PARKED
(Linux)
psutil.
REALTIME_PRIORITY_CLASS
¶
psutil.
HIGH_PRIORITY_CLASS
¶
psutil.
ABOVE_NORMAL_PRIORITY_CLASS
¶
psutil.
NORMAL_PRIORITY_CLASS
¶
psutil.
IDLE_PRIORITY_CLASS
¶
psutil.
BELOW_NORMAL_PRIORITY_CLASS
¶
Represent the priority of a process on Windows (see
SetPriorityClass
). They can be used in conjunction with
psutil.Process.nice()
to get or set process priority.
可用性:Windows
psutil.
IOPRIO_CLASS_NONE
¶
psutil.
IOPRIO_CLASS_RT
¶
psutil.
IOPRIO_CLASS_BE
¶
psutil.
IOPRIO_CLASS_IDLE
¶
A set of integers representing the I/O priority of a process on Linux. They can be used in conjunction with
psutil.Process.ionice()
to get or set process I/O priority.
IOPRIO_CLASS_NONE
and
IOPRIO_CLASS_BE
(best effort) is the default for any process that hasn’t set a specific I/O priority.
IOPRIO_CLASS_RT
(real time) means the process is given first access to the disk, regardless of what else is going on in the system.
IOPRIO_CLASS_IDLE
means the process will get I/O time when no-one else needs the disk. For further information refer to manuals of
ionice
command line utility or
ioprio_get
系统调用。
可用性:Linux
psutil.
IOPRIO_VERYLOW
¶
psutil.
IOPRIO_LOW
¶
psutil.
IOPRIO_NORMAL
¶
psutil.
IOPRIO_HIGH
¶
A set of integers representing the I/O priority of a process on Windows. They can be used in conjunction with
psutil.Process.ionice()
to get or set process I/O priority.
可用性:Windows
5.6.2 版新增。
Linux / FreeBSD:
psutil.
RLIM_INFINITY
¶
psutil.
RLIMIT_AS
¶
psutil.
RLIMIT_CORE
¶
psutil.
RLIMIT_CPU
¶
psutil.
RLIMIT_DATA
¶
psutil.
RLIMIT_FSIZE
¶
psutil.
RLIMIT_MEMLOCK
¶
psutil.
RLIMIT_NOFILE
¶
psutil.
RLIMIT_NPROC
¶
psutil.
RLIMIT_RSS
¶
psutil.
RLIMIT_STACK
¶
Linux 特有:
psutil.
RLIMIT_LOCKS
¶
psutil.
RLIMIT_MSGQUEUE
¶
psutil.
RLIMIT_NICE
¶
psutil.
RLIMIT_RTPRIO
¶
psutil.
RLIMIT_RTTIME
¶
psutil.
RLIMIT_SIGPENDING
¶
FreeBSD 特有:
psutil.
RLIMIT_SWAP
¶
psutil.
RLIMIT_SBSIZE
¶
psutil.
RLIMIT_NPTS
¶
Constants used for getting and setting process resource limits to be used in conjunction with
psutil.Process.rlimit()
。见
resource.getrlimit
了解进一步信息。
可用性:Linux、FreeBSD
5.7.3 版改变:
added FreeBSD support, added
RLIMIT_SWAP
,
RLIMIT_SBSIZE
,
RLIMIT_NPTS
.
psutil.
CONN_ESTABLISHED
¶
psutil.
CONN_SYN_SENT
¶
psutil.
CONN_SYN_RECV
¶
psutil.
CONN_FIN_WAIT1
¶
psutil.
CONN_FIN_WAIT2
¶
psutil.
CONN_TIME_WAIT
¶
psutil.
CONN_CLOSE
¶
psutil.
CONN_CLOSE_WAIT
¶
psutil.
CONN_LAST_ACK
¶
psutil.
CONN_LISTEN
¶
psutil.
CONN_CLOSING
¶
psutil.
CONN_NONE
¶
psutil.
CONN_DELETE_TCB
(
Windows
)
¶
psutil.
CONN_IDLE
(
Solaris
)
¶
psutil.
CONN_BOUND
(
Solaris
)
¶
A set of strings representing the status of a TCP connection. Returned by
psutil.Process.connections()
and
psutil.net_connections()
(
status
字段)。
psutil.
AF_LINK
¶
Constant which identifies a MAC address associated with a network interface. To be used in conjunction with
psutil.net_if_addrs()
.
3.0.0 版新增。
psutil.
NIC_DUPLEX_FULL
¶
psutil.
NIC_DUPLEX_HALF
¶
psutil.
NIC_DUPLEX_UNKNOWN
¶
Constants which identifies whether a NIC (network interface card) has full or half mode speed. NIC_DUPLEX_FULL means the NIC is able to send and receive data (files) simultaneously, NIC_DUPLEX_FULL means the NIC can either send or receive data at a time. To be used in conjunction with
psutil.net_if_stats()
.
3.0.0 版新增。
psutil.
POWER_TIME_UNKNOWN
¶
psutil.
POWER_TIME_UNLIMITED
¶
Whether the remaining time of the battery cannot be determined or is unlimited. May be assigned to
psutil.sensors_battery()
’s
secsleft
字段。
5.1.0 版新增。
psutil.
version_info
¶
用于校验 psutil 安装版本的元组。范例:
>>> import psutil >>> if psutil.version_info >= (4, 5): ... pass
校验字符串针对
Process.name()
:
import psutil def find_procs_by_name(name): "Return a list of processes matching 'name'." ls = [] for p in psutil.process_iter(['name']): if p.info['name'] == name: ls.append(p) return ls
更高级一点,校验字符串对
Process.name()
,
Process.exe()
and
Process.cmdline()
:
import os import psutil def find_procs_by_name(name): "Return a list of processes matching 'name'." ls = [] for p in psutil.process_iter(["name", "exe", "cmdline"]): if name == p.info['name'] or \ p.info['exe'] and os.path.basename(p.info['exe']) == name or \ p.info['cmdline'] and p.info['cmdline'][0] == name: ls.append(p) return ls
import os import signal import psutil def kill_proc_tree(pid, sig=signal.SIGTERM, include_parent=True, timeout=None, on_terminate=None): """Kill a process tree (including grandchildren) with signal "sig" and return a (gone, still_alive) tuple. "on_terminate", if specified, is a callback function which is called as soon as a child terminates. """ assert pid != os.getpid(), "won't kill myself" parent = psutil.Process(pid) children = parent.children(recursive=True) if include_parent: children.append(parent) for p in children: try: p.send_signal(sig) except psutil.NoSuchProcess: pass gone, alive = psutil.wait_procs(children, timeout=timeout, callback=on_terminate) return (gone, alive)
A collection of code samples showing how to use
process_iter()
to filter processes and sort them. Setup:
>>> import psutil >>> from pprint import pprint as pp
由用户拥有的进程:
>>> import getpass >>> pp([(p.pid, p.info['name']) for p in psutil.process_iter(['name', 'username']) if p.info['username'] == getpass.getuser()]) (16832, 'bash'), (19772, 'ssh'), (20492, 'python')]
Processes actively running:
>>> pp([(p.pid, p.info) for p in psutil.process_iter(['name', 'status']) if p.info['status'] == psutil.STATUS_RUNNING]) [(1150, {'name': 'Xorg', 'status': 'running'}), (1776, {'name': 'unity-panel-service', 'status': 'running'}), (20492, {'name': 'python', 'status': 'running'})]
Processes using log files:
>>> for p in psutil.process_iter(['name', 'open_files']): ... for file in p.info['open_files'] or []: ... if file.path.endswith('.log'): ... print("%-5s %-10s %s" % (p.pid, p.info['name'][:10], file.path)) ... 1510 upstart /home/giampaolo/.cache/upstart/unity-settings-daemon.log 2174 nautilus /home/giampaolo/.local/share/gvfs-metadata/home-ce08efac.log 2650 chrome /home/giampaolo/.config/google-chrome/Default/data_reduction_proxy_leveldb/000003.log
Processes consuming more than 500M of memory:
>>> pp([(p.pid, p.info['name'], p.info['memory_info'].rss) for p in psutil.process_iter(['name', 'memory_info']) if p.info['memory_info'].rss > 500 * 1024 * 1024]) [(2650, 'chrome', 532324352), (3038, 'chrome', 1120088064), (21915, 'sublime_text', 615407616)]
Top 3 processes which consumed the most CPU time:
>>> pp([(p.pid, p.info['name'], sum(p.info['cpu_times'])) for p in sorted(psutil.process_iter(['name', 'cpu_times']), key=lambda p: sum(p.info['cpu_times'][:2]))][-3:]) [(2721, 'chrome', 10219.73), (1150, 'Xorg', 11116.989999999998), (2650, 'chrome', 18451.97)]
import psutil def bytes2human(n): # http://code.activestate.com/recipes/578019 # >>> bytes2human(10000) # '9.8K' # >>> bytes2human(100001221) # '95.4M' symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') prefix = {} for i, s in enumerate(symbols): prefix[s] = 1 << (i + 1) * 10 for s in reversed(symbols): if n >= prefix[s]: value = float(n) / prefix[s] return '%.1f%s' % (value, s) return "%sB" % n total = psutil.disk_usage('/').total print(total) print(bytes2human(total))
…prints:
100399730688 93.5G
AccessDenied
for certain processes?
ps
and
netstat
does this). On Windows you may run the Python process as NT AUTHORITY\SYSTEM or install the Python script as a Windows service (ProcessHacker does this).
$ python3 -m psutil.tests
If you want to debug unusual situations or want to report a bug, it may be useful to enable debug mode via
PSUTIL_DEBUG
environment variable. In this mode, psutil may (or may not) print additional information to stderr. Usually these are error conditions which are not severe, and hence are ignored (instead of crashing). Unit tests automatically run with debug mode enabled. On UNIX:
$ PSUTIL_DEBUG=1 python3 script.py psutil-debug [psutil/_psutil_linux.c:150]> setmntent() failed (ignored)
在 Windows:
set PSUTIL_DEBUG=1 python.exe script.py psutil-debug [psutil/arch/windows/process_info.c:90]> NtWow64ReadVirtualMemory64(pbi64.PebBaseAddress) -> 998 (Unknown error) (ignored)
要报告安全脆弱性,请使用 Tidelift 安全性联络 。Tidelift 将协调修复并披露。
若想要开发 psutil,查看 开发指南 .
支持的 Python 版本为 2.7、3.4+ 和 PyPy3。