psutil库
psutil是一个非常强大的第三方库,用法简单,这里主要是做一下梳理。
先看看官方说明:
psutil (python system and process utilities) is a cross-platform library for retrieving information on running processes and system utilization (CPU, memory, disks, network, sensors) in Python.
It is useful mainly for system monitoring, profiling, limiting process resources and the management of running processes.
It implements many functionalities offered by UNIX command line tools such as: ps, top, lsof, netstat, ifconfig, who, df, kill, free, nice, ionice, iostat, iotop, uptime, pidof, tty, taskset, pmap.
psutil是一个跨平台库,可以获取系统硬件利用率(包括CPU, memory, disks, network, sensors)和正在运行的进程的信息。主要用于系统资源监控和进程管理。
安装psutil:
# pip3 install psutil
>>> import psutil
>>> dir(psutil)
['AF_LINK', 'AIX', 'AccessDenied', 'BSD', 'CONN_CLOSE', 'CONN_CLOSE_WAIT', 'CONN_CLOSING', 'CONN_ESTABLISHED', 'CONN_FIN_WAIT1', 'CONN_FIN_WAIT2', 'CONN_LAST_ACK', 'CONN_LISTEN', 'CONN_NONE', 'CONN_SYN_RECV', 'CONN_SYN_SENT', 'CONN_TIME_WAIT', 'Error', 'FREEBSD', 'IOPRIO_CLASS_BE', 'IOPRIO_CLASS_IDLE', 'IOPRIO_CLASS_NONE', 'IOPRIO_CLASS_RT', 'LINUX', 'NETBSD', 'NIC_DUPLEX_FULL', 'NIC_DUPLEX_HALF', 'NIC_DUPLEX_UNKNOWN', 'NoSuchProcess', 'OPENBSD', 'OSX', 'POSIX', 'POWER_TIME_UNKNOWN', 'POWER_TIME_UNLIMITED', 'PROCFS_PATH', 'Popen', 'Process', 'RLIMIT_AS', 'RLIMIT_CORE', 'RLIMIT_CPU', 'RLIMIT_DATA', 'RLIMIT_FSIZE', 'RLIMIT_LOCKS', 'RLIMIT_MEMLOCK', 'RLIMIT_MSGQUEUE', 'RLIMIT_NICE', 'RLIMIT_NOFILE', 'RLIMIT_NPROC', 'RLIMIT_RSS', 'RLIMIT_RTPRIO', 'RLIMIT_RTTIME', 'RLIMIT_SIGPENDING', 'RLIMIT_STACK', 'RLIM_INFINITY', 'STATUS_DEAD', 'STATUS_DISK_SLEEP', 'STATUS_IDLE', 'STATUS_LOCKED', 'STATUS_RUNNING', 'STATUS_SLEEPING', 'STATUS_STOPPED', 'STATUS_TRACING_STOP', 'STATUS_WAITING', 'STATUS_WAKING', 'STATUS_ZOMBIE', 'SUNOS', 'TimeoutExpired', 'WINDOWS', 'ZombieProcess', '_PY3', '_TOTAL_PHYMEM', '__all__', '__author__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', '_as_dict_attrnames', '_assert_pid_not_reused', '_common', '_compat', '_cpu_busy_time', '_cpu_tot_time', '_last_cpu_times', '_last_cpu_times_2', '_last_per_cpu_times', '_last_per_cpu_times_2', '_pmap', '_pslinux', '_psplatform', '_psposix', '_psutil_linux', '_psutil_posix', '_timer', '_wrap_numbers', 'boot_time', 'callable', 'collections', 'contextlib', 'cpu_count', 'cpu_percent', 'cpu_stats', 'cpu_times', 'cpu_times_percent', 'disk_io_counters', 'disk_partitions', 'disk_usage', 'errno', 'functools', 'long', 'net_connections', 'net_if_addrs', 'net_if_stats', 'net_io_counters', 'os', 'pid_exists', 'pids', 'process_iter', 'pwd', 'sensors_battery', 'sensors_fans', 'sensors_temperatures', 'signal', 'subprocess', 'swap_memory', 'sys', 'test', 'time', 'traceback', 'users', 'version_info', 'virtual_memory', 'wait_procs']
用法如下:
CPU
psutil.cpu_times(percpu=False)
psutil.cpu_percent(interval=None, percpu=False)
psutil.cpu_times_percent(interval=None, percpu=False)
psutil.cpu_stats()
psutil.cpu_freq(percpu=False)
psutil.cpu_count(logical=True):获取CPU个数或核心数。
Return the number of logical CPUs in the system (same as os.cpu_count() in Python 3.4) or None if undetermined.
This number may not be equivalent to the number of CPUs the current process can actually use in case process CPU affinity has been changed or Linux cgroups are being used.
The number of usable CPUs can be obtained with len(psutil.Process().cpu_affinity()).
If logical is False return the number of physical cores only
Memory
psutil.virtual_memory():获取内存的使用信息。
psutil.swap_memory():获取交换内存的使用信息。
Disk
psutil.disk_partitions(all=False):获取硬盘分区信息。
psutil.disk_usage(path):获取硬盘使用信息。
psutil.disk_io_counters(perdisk=False, nowrap=True):获取磁盘IO信息。
Network
psutil.net_io_counters(pernic=False):获取网络IO信息。
psutil.net_connections(kind='inet'):获取socket连接信息。
psutil.net_if_addrs():获取各网卡的各种地址信息(包括IP地址、网络地址、广播地址等)。
psutil.net_if_stats():获取网卡的硬件信息(包括是否启用、单工还是双工、speed、MTU)。
Sensor
psutil.sensors_temperatures(fahrenheit=False):获取硬件的温度(包括CPU、硬盘等)。
psutil.sensors_fans():获取风扇的转速。
psutil.sensors_battery():获取电池状态信息。
其它系统信息
psutil.boot_time():获取系统的启动时间,注意不是启动时长,是启动时的时间戳。
psutil.users():获取当前登录系统的用户。
Process,获取进程信息
psutil.pids():获取系统当前正在运行的所有PID。返回的是一个进程号列表。
psutil.pid_exists(pid):检测指定的pid是否存在。
psutil.wait_procs(procs, timeout=None, callback=None):等待进程结束。
psutil.process_iter(attrs=None, ad_value=None):返回一个生成器,迭代获取所有进程的属性信息,可以用attrs指定要显示的属性,然后调用`Process.as_dict()`方法即可获取相关属性。
>>> psutil.process_iter()
<generator object process_iter at 0x7f5321d8e468>
>>> p = psutil.process_iter()
>>> for i in p:
... print(i)
...
psutil.Process(pid=1, name='systemd')
psutil.Process(pid=2, name='kthreadd')
psutil.Process(pid=3, name='ksoftirqd/0')
psutil.Process(pid=5, name='kworker/0:0H')
... ...
psutil.Process(pid=32284, name='bioset')
psutil.Process(pid=32285, name='dm-thin')
psutil.Process(pid=32286, name='bioset')
Process class
class psutil.Process(pid=None):Process类。
Represents an OS process with the given pid. If pid is omitted current process pid (os.getpid()) is used. Raise NoSuchProcess if pid does not exist.
pid:The process PID. This is the only (read-only) attribute of the class.
ppid():The process parent PID.
name():The process name.
exe():The process executable as an absolute path.
cmdline():The command line this process has been called with as a list of strings. The return value is not cached because the cmdline of a process may change.
environ():The environment variables of the process as a dict. Note: this might not reflect changes made after the process started.
create_time():The process creation time as a floating point number expressed in seconds since the epoch, in UTC. The return value is cached after first call.
parent():Utility method which returns the parent process as a Process object preemptively checking whether PID has been reused. If no parent PID is known return None.
status():The current process status as a string.
cwd():The process current working directory as an absolute path.
username():The name of the user that owns the process. On UNIX this is calculated by using real process uid.
uids():The real, effective and saved user ids of this process as a named tuple.
gids():The real, effective and saved group ids of this process as a named tuple.
terminal():The terminal associated with this process, if any, else None.
io_counters():Return process I/O statistics as a named tuple.
num_fds():The number of file descriptors currently opened by this process (non cumulative).
num_handles():The number of handles currently used by this process (non cumulative).
num_threads():The number of threads currently used by this process (non cumulative).
threads():Return threads opened by process as a list of named tuples including thread id and thread CPU times (user/system).
cpu_times():Return a (user, system, children_user, children_system) named tuple representing the accumulated process time, in seconds.
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.
cpu_affinity(cpus=None):Get or set process current CPU affinity. CPU affinity consists in telling the OS to run a process on a limited set of CPUs only. 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).
cpu_num():Return what CPU this process is currently running on.
memory_info():Return a named tuple with variable fields depending on the platform representing memory information about the process.
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() (defaults to "rss").
children(recursive=False):Return the children of this process as a list of Process objects, preemptively checking whether PID has been reused. If recursive is True return all the parent descendants.
open_files():Return regular files opened by process as a list of named tuples.
connections(kind="inet"):Return socket connections opened by process as a list of named tuples.
is_running():Return whether the current process is running in the current process list.
send_signal(signal):Send a signal to process preemptively checking whether PID has been reused.
suspend():Suspend process execution with SIGSTOP signal preemptively checking whether PID has been reused.
resume():Resume process execution with SIGCONT signal preemptively checking whether PID has been reused.
terminate():Terminate the process with SIGTERM signal preemptively checking whether PID has been reused.
kill():Kill the current process by using SIGKILL signal preemptively checking whether PID has been reused.
wait(timeout=None):Wait for process termination and if the process is a children of the current one also return the exit code, else None. To wait for multiple processes use psutil.wait_procs().
Popen class
class psutil.Popen(*args, **kwargs):Popen类。
A more convenient interface to stdlib subprocess.Popen. It starts a sub process and you deal with it exactly as when using subprocess.Popen but in addition it also provides all the methods of psutil.Process class.
是一个比subprocess.Popen标准库更方便的接口。它启动一个子进程,使用方法与 subprocess.Popen 完全相同,不过它提供所有 psutil.Process 的类,所以它的使用方法除了上面列出的方法,还需要参考 subprocess.Popen 支持的方法。不同的是,它会事先检查PID是否被复用,不会意外杀掉其它进程。
>>> import psutil
>>> from subprocess import PIPE
>>> p = psutil.Popen(["/usr/bin/python", "-c", "print('hello')"], stdout=PIPE)
>>>
>>> p.name()
'python'
>>> p.username()
'root'
>>> p.communicate()
(b'hello\n', None)
>>> p.wait()
0
需要总结一下的是,subprocess和psutil.Popen常用来调用外部命令,也就是执行系统命令,进程间只能通过管道进行文本交流,从上面例子中的 PIPE 可见一斑,这里可以阅读一下subprocess的官方文档便知。
另外,常用来调用系统命令的接口还有 os.system()和os.popen(),不过设计和使用上更简单一些。
官方文档非常详细,其它细节请查阅官方文档。
参考:
http://psutil.readthedocs.io/en/latest/
https://pypi.python.org/pypi/psutil/
https://docs.python.org/3/library/subprocess.html
psutil库的更多相关文章
- 使用psutil库监控linux的系统资源和自定义进程的cpu 内存占用。
#coding=utf8 import time import psutil from pprint import pprint from logger_until import LoggerUnti ...
- python自动化运维笔记1 —— 系统性能信息模块psutil
一.系统基础信息模块 1.1 系统性能信息模块psutil psutil是一个跨平台库(http://code.google.com/p/psutil/),能够轻松实现获取系统运行的进程和系统利用率( ...
- python运维开发常用模块(一)psutil
1.模块简介 psutil是一个跨平台库(http://code.google.com/p/psutil/),能够轻 松实现获取系统运行的进程和系统利用率(包括CPU.内存.磁盘.网 络等)信息.它主 ...
- what's the psutil模块
what's the psutil模块 psutil 是一个跨平台库,能够轻松实现获取系统运行的进程和系统利用率(包括CPU.内存.磁盘.网络等)信息.它主要用来做系统监控,性能分析,进程管理.它实现 ...
- 系统性能信息模块psutil
目录 前言 获取系统性能信息 CPU 内存 磁盘 网络信息 其他系统信息 系统进程管理方法 进程信息 popen类 查看系统硬件的小脚本 前言 psutil 是一个跨平台库,能够轻松实现获取系统运行的 ...
- Python对系统数据进行采集监控——psutil
大家好,我是辰哥- 今天给大家介绍一个可以获取当前系统信息的库--psutil 利用psutil库可以获取系统的一些信息,如cpu,内存等使用率,从而可以查看当前系统的使用情况,实时采集这些信息可以达 ...
- flask+sqlite3+echarts3 系统监控
总的而言,分三部分: 1.监控器(monitor.py): 每秒获取系统的四个cpu的使用率,存入数据库. 2.路由器(app.py): 响应页面的ajax,获取最新的一条或多条数据. 3.页面(in ...
- 借助Glances Monitor,密切关注你的系统
两种方法安装 glances 通常可以有两种方法安装 glances.第一种是通过编译源代码的方式,这种方法比较复杂另外可能会遇到软件包依赖性问题.还有一种是使用特定的软件包管理工具来安装 glanc ...
- Python的学习
1.psutil的安装 [root@YQY-TIAN- ~]# wget https://pypi.python.org/packages/source/p/psutil/psutil-2.0.0.t ...
随机推荐
- kettle学习笔记(五)——kettle输出步骤
一.概述 数据库表: • 表输出 • 更新,删除,插入/更新 • 批量加载(mysql,oracle) • 数据同步 文件: • SQL 文件输出 • 文本文件输出 • XML 输出 • Excel ...
- JavaEE笔记(十)
#Spring 为了配置bean对象和维护bean对象之间关系的一个容器框架 #三种注入方法 1 Setter注入2 构造参数注入3 注解注入(原理同1) #自动装配(autowire) 模式 说明 ...
- Linux下的openvpn配置 与 easy-rsa3的证书生成
#注意:以下操作由服务端操作即可#PS:为什么我找不到var文件??============安装===============wget -O /etc/yum.repos.d/epel.repo ht ...
- CS190.1x Scalable Machine Learning
这门课是CS100.1x的后续课,看课程名字就知道这门课主要讲机器学习.难度也会比上一门课大一点.如果你对这门课感兴趣,可以看看我这篇博客,如果对PySpark感兴趣,可以看我分析作业的博客. Cou ...
- SQL SERVER 2008R2 安装问题
背景 今天帮可以安装数据库.操作系统是windows server 2012 标准版, 安装SQL SERVER 2008R2 . 运行安装程序,提示如下 这是因为两者之间存在兼容性问题. ...
- Ubuntu16.04+Java8+Mysql5.7+Tomcat8.5服务器环境配置
本文章使用环境: Ubuntu16.04 Java8 Mysql5.7 Tomcat8.5 Ubuntu 版本16.04, 本文采用SSH远程登录主机 工具:Xshell 默认使用root用户登录 ( ...
- Spark RDD深度解析-RDD计算流程
Spark RDD深度解析-RDD计算流程 摘要 RDD(Resilient Distributed Datasets)是Spark的核心数据结构,所有数据计算操作均基于该结构进行,包括Spark ...
- Linux 终端快捷键整理
一.历史命令相关快捷键 快捷键 说明 ↑.↓ 显示历史命令 !! 执行上一个命令 !n 执行历史命令中第 n 条命令 !-n 执行历史命令中倒数第 n 条命令 二.移动相关快捷键 快捷键 说明 Ctr ...
- [Hanani]JAVA大数相关学习记录
1.Basic remains 题目链接 涉及内容: |大数读入|大数模|大数进制读入时转化为十进制|大数输出时转化为其他进制输出| import java.io.*; import java.mat ...
- Bitcoin挖矿
目录 为什么要挖矿? 比特币挖矿 为什么要挖矿? 增加恶意行为的成本 增加记账权力,获取相应的奖励 比特币挖矿 每开采210000个区块,挖矿奖励减半 2009年1月-2012年11月,奖励50BTC ...