码迷,mamicode.com
首页 > 其他好文 > 详细

系统性能信息模块 psutil

时间:2019-06-19 18:38:27      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:tfs   oca   sdi   查看内存   pre   dev   就是   https   port   

用于分析系统资源的工具, 如CPU, 内存,磁盘,网络等

参考文档 <https://www.liaoxuefeng.com/wiki/1016959663602400/1183565811281984>; 或 python自动化运维 技术与最佳实践

安装

pip install psutil 

使用

导入模块 import psutil

查看内存

# 查看内存状态
mem = psutil.virtual_memory()   # 单位长度 字节   转换需要除以三次 (k m g)
# svmem(total=13958176768, available=8882548736, percent=36.4, used=5075628032, free=8882548736)

# round 四舍五入,  获取2位长度,
total = round(mem.total / 1024 / 1024 / 1024, 2)
print(total)

查看CPU

# 获取 CPU 逻辑个数
cpuCount = psutil.cpu_count()     # 4

# 获取 CPU 物理个数
print(psutil.cpu_count(logical=False))   # 4

# percpu=True 显示所有CPU 运行的所有时间
cpuTime = psutil.cpu_times(percpu=True)
print(cpuTime)

查看磁盘

# 查看磁盘格式以及挂载点
print(psutil.disk_partitions())
# [sdiskpart(device=‘C:\\‘, mountpoint=‘C:\\‘, fstype=‘NTFS‘, opts=‘rw,fixed‘),
#         sdiskpart(device=‘D:\\‘, mountpoint=‘D:\\‘, fstype=‘UDF‘, opts=‘ro,cdrom‘)]

# 查看具体的磁盘大小以及使用情况
print(psutil.disk_usage(‘C:\\‘))
# sdiskusage(total=34252779520, used=25038110720, free=9214668800, percent=73.1)

# 循环出磁盘格式为NTFS的 == windows机器, percent使用的百分比
for device in psutil.disk_partitions():
    if device.fstype == "NTFS":
        print(psutil.disk_usage(device.device).percent)

查看网络连接数

# 所有的连接
psutil.net_connections()

查看进程

>>> psutil.pids() # 所有进程ID
[3865, 3864, 3863, 3856, 3855, 3853, 3776, ..., 45, 44, 1, 0]
>>> p = psutil.Process(3776) # 获取指定进程ID=3776,其实就是当前Python交互环境
>>> p.name() # 进程名称
‘python3.6‘
>>> p.exe() # 进程exe路径
‘/Users/michael/anaconda3/bin/python3.6‘
>>> p.cwd() # 进程工作目录
‘/Users/michael‘
>>> p.cmdline() # 进程启动的命令行
[‘python3‘]
>>> p.ppid() # 父进程ID
3765
>>> p.parent() # 父进程
<psutil.Process(pid=3765, name=‘bash‘) at 4503144040>
>>> p.children() # 子进程列表
[]
>>> p.status() # 进程状态
‘running‘
>>> p.username() # 进程用户名
‘michael‘
>>> p.create_time() # 进程创建时间
1511052731.120333
>>> p.terminal() # 进程终端
‘/dev/ttys002‘
>>> p.cpu_times() # 进程使用的CPU时间
pcputimes(user=0.081150144, system=0.053269812, children_user=0.0, children_system=0.0)
>>> p.memory_info() # 进程使用的内存
pmem(rss=8310784, vms=2481725440, pfaults=3207, pageins=18)
>>> p.open_files() # 进程打开的文件
[]
>>> p.connections() # 进程相关网络连接
[]
>>> p.num_threads() # 进程的线程数量
1
>>> p.threads() # 所有线程信息
[pthread(id=1, user_time=0.090318, system_time=0.062736)]
>>> p.environ() # 进程环境变量
{‘SHELL‘: ‘/bin/bash‘, ‘PATH‘: ‘/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:...‘, ‘PWD‘: ‘/Users/michael‘, ‘LANG‘: ‘zh_CN.UTF-8‘, ...}
>>> p.terminate() # 结束进程
Terminated: 15 <-- 自己把自己结束了

系统性能信息模块 psutil

标签:tfs   oca   sdi   查看内存   pre   dev   就是   https   port   

原文地址:https://blog.51cto.com/xiong51/2411179

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!