更多见官方文档:https://psutil.readthedocs.io/en/latest/#running-tests
进程操作相关
import psutil
"""进程相关"""
"""返回当前运行的 pid 的排序列表"""
res = psutil.pids()
# print(res)
"""迭代返回返回当前运行的 pid 并指定返回信息字段"""
for i in psutil.process_iter(["pid", "name", "cmdline"]):
for file in i.info.get("cmdline"):
if "locustfile" in file:
print("#"*100)
print(i.info)
# sutil.Process(pid=79, name='deferwq', status='sleeping', started='2021-12-23 23:44:38')
# psutil.Process(pid=134, name='ttm_swap', status='sleeping', started='2021-12-23 23:44:38')
# psutil.Process(pid=255, name='ata_sff', status='sleeping', started='2021-12-23 23:44:38')
# psutil.Process(pid=257, name='scsi_eh_0', status='sleeping', started='2021-12-23 23:44:38')
# psutil.Process(pid=258, name='scsi_tmf_0', status='sleeping', started='2021-12-23 23:44:38')
# psutil.Process(pid=259, name='scsi_eh_1', status='sleeping', started='2021-12-23 23:44:38')
# 迭代返回返回当前运行的 pid 但不指定返回信息字段
for i in psutil.process_iter([]):
"""
返回实例
{'environ': None, 'io_counters': None, 'status': 'stopped', 'uids': puids(real=72, effective=72, saved=72), 'num_ctx_switches': pctxsw(voluntary=132, involuntary=9), 'memory_maps': None, 'nice': 0, 'cpu_affinity': [0, 1, 2, 3], 'terminal': None, 'cwd': None, 'num_fds': None, 'cpu_percent': 0.0, 'connections': None, 'threads': [pthread(id=32403, user_time=0.0, system_time=0.01)], 'memory_full_info': None, 'cpu_times': pcputimes(user=0.0, system=0.01, children_user=0.0, children_system=0.0, iowait=0.0), 'username': 'tcpdump', 'ppid': 19602, 'exe': None, 'gids': pgids(real=72, effective=72, saved=72), 'create_time': 1642175058.53, 'num_threads': 1, 'pid': 32403, 'cmdline': ['tcpdump', 'port', '8080'], 'name': 'tcpdump', 'cpu_num': 2, 'memory_percent': 0.07080809109775511, 'ionice': pionice(ioclass=<IOPriority.IOPRIO_CLASS_NONE: 0>, value=4), 'open_files': None, 'memory_info': pmem(rss=5808128, vms=751656960, shared=3969024, text=671744, lib=0, data=707502080, dirty=0)}
"""
print(i.info)
print("#"*90)
"""检查当前进程列表中是否存在给定pid,False不存在,True存在"""
res = psutil.pid_exists(8089)
print(res) # False
print("检查进程是否在运行中:", psutil.Process(8790).is_running()) # 检查进程是否在运行中: True
print("挂起进程:", psutil.Process(8790).suspend()) # 检查进程是否在被挂起: None
print("终止进程:", psutil.Process(8790).terminate()) # 检查进程是否被终止: None
print("杀死当前进程:", psutil.Process(8790).kill()) # 杀死当前进程: None
# {'status': 'sleeping', 'pid': 8790, 'name': 'locust', 'username': 'work'}
print(psutil.Process(8790).as_dict(attrs=["pid", "name", "username", "status"]))
print("返回进程可执行文件的绝对路径", psutil.Process(8790).exe())
# /home/users/work/.jumbo/bin/python3.6
print("返回该进程执行的命令行调用列表:", psutil.Process(8790).cmdline())
# ['/home/work/baidu/personal-code/wanshunzhe-script/env/bin/python', '/home/work/baidu/personal-code/wanshunzhe-script/env/bin/locust', '-f', '/home/work/baidu/personal-code/wanshunzhe-script/wanshunzhe_script/perf_test/demo/locustfile.py', '--web-host=0.0.0.0', '-P', '8878']
print("返回进程信息可检索字段--字典类型:", list(psutil.Process().as_dict().keys()))
# ['name', 'uids', 'num_ctx_switches', 'threads', 'memory_maps', 'memory_info', 'create_time', 'exe', 'cpu_times', 'cwd', 'status', 'username', 'cpu_num', 'connections', 'ionice', 'pid', 'open_files', 'io_counters', 'gids', 'memory_percent', 'terminal', 'ppid', 'num_fds', 'cpu_affinity', 'nice', 'environ', 'cpu_percent', 'cmdline', 'num_threads', 'memory_full_info']
print("返回当前进程绝对路径的工作目录:", psutil.Process(8790).cwd())
# 返回当前进程绝对路径的工作目录: /home/work/baidu/personal-code/wanshunzhe-script
###########################CPU###########################
p = psutil.Process(8790)
with p.oneshot():
print(p.name())
print(p.cpu_times())
print(p.create_time())
print(p.ppid())
print(p.status())
print("返回进程打开的文件:", psutil.Process(8790).open_files())
CPU
import psutil
"""CPU利用率:返回一个浮点数,表示进程 CPU 利用率的百分比,如果一个进程在不同的 CPU 上运行多个线程,这个百分比也可以大于100.0,
建议在两次调用之间至少有0.1秒的时间"""
print("CPU利用率:", psutil.Process(8790).cpu_percent(interval=0.1))
# CPU利用率: 10.0
print("返回此进程当前运行的 CPU:", psutil.Process(8790).cpu_num())
# 返回此进程当前运行的 CPU: 2
内存
import psutil
"""内存
rss: 又名“驻留设置大小”,这是一个进程使用的非交换物理内存。在 UNIX 上,它匹配“ top”的 RES 列
vms: 又名“虚拟内存大小”,这是进程使用的虚拟内存总量。在 UNIX 上,它匹配“ top”的 VIRT 列
shared: (Linux)可以与其他进程共享的内存。这与“ top”的 SHR 列相匹配
text: aka TRS (text resident set)用于执行代码的内存量。这与“ top”的 CODE 列相匹配
data: 又名 DRS (数据驻留集)的物理内存量专门用于其他可执行代码。它与“ top”的 DATA 列相匹配
lib: 共享库使用的内存
dirty: 脏页的数量
swap: 已交换到磁盘的内存量
"""
print("返回当前进程内存信息:", psutil.Process(8790).memory_info())
# 返回当前进程内存信息: pmem(rss=103419904, vms=1141624832, shared=7708672, text=4096, lib=0, data=847384576, dirty=0)
print("此方法返回与 memory _ info ()相同的信息: ", psutil.Process(8790).memory_full_info())
# 此方法返回与 memory _ info ()相同的信息: pfullmem(rss=118353920, vms=1156218880, shared=7708672, text=4096, lib=0, data=861978624, dirty=0, uss=110796800, pss=111862784, swap=0)
print("内存利用率:", psutil.Process(8790).memory_percent(memtype="rss"))
# 内存利用率: 1.442877145465186
网络
import psutil
print("返回进程打开的套接字连接列表:", psutil.Process(8790).connections(kind="inet"))
实践例子
实现一个根据匹配进程cmdline,删除指定进程