Python利用psutil库进行监控进程和资源

 更新时间:2024年01月31日 08:47:14   作者:Sitin涛哥  
psutil是Python系统和进程工具库,它提供了一种跨平台的方式来获取系统信息、管理系统进程、监控系统性能、操作系统资源等,下面就跟随小编一起来学习psutil库的具体应用吧

Python作为一门强大的编程语言,拥有丰富的标准库和第三方库,使得开发者可以轻松完成各种任务。在系统监控和管理方面,psutil库无疑是一个强大的工具,它可以轻松地获取系统信息、管理进程、监控系统性能等。本文将深入探讨psutil库,介绍它的基本概念、用法和示例代码,帮助大家更好地理解和利用这个强大的库。

什么是psutil库

psutil是Python系统和进程工具库(Python System and Process Utilities)。它提供了一种跨平台的方式来获取系统信息、管理系统进程、监控系统性能、操作系统资源等。无论是在Windows、Linux还是macOS,psutil都能提供一致的API,使得开发者可以轻松地编写跨平台的代码。

安装psutil库

要开始使用psutil库,首先需要安装它。

可以使用pip来进行安装:

pip install psutil

安装完成后,就可以导入并开始使用psutil库了。

import psutil

获取系统信息

获取CPU信息

import psutil

# 获取CPU核心数
cpu_count = psutil.cpu_count(logical=False)
print(f"Physical CPU Count: {cpu_count}")

# 获取逻辑CPU核心数(包括超线程)
logical_cpu_count = psutil.cpu_count(logical=True)
print(f"Logical CPU Count: {logical_cpu_count}")

# 获取CPU使用率
cpu_usage = psutil.cpu_percent(interval=1, percpu=True)
for i, usage in enumerate(cpu_usage, 1):
    print(f"CPU {i} Usage: {usage}%")

获取内存信息

import psutil

# 获取内存总量
total_memory = psutil.virtual_memory().total
print(f"Total Memory: {total_memory / (1024 ** 3):.2f} GB")

# 获取可用内存
available_memory = psutil.virtual_memory().available
print(f"Available Memory: {available_memory / (1024 ** 3):.2f} GB")

# 获取内存使用率
memory_usage = psutil.virtual_memory().percent
print(f"Memory Usage: 1.15MB%")

获取磁盘信息

import psutil

# 获取所有磁盘分区信息
disk_partitions = psutil.disk_partitions()
for partition in disk_partitions:
    print(f"Device: {partition.device}")
    print(f"Mountpoint: {partition.mountpoint}")
    print(f"Fstype: {partition.fstype}")
    print("")

# 获取指定分区的使用情况
disk_usage = psutil.disk_usage("/")
print(f"Total: {disk_usage.total / (1024 ** 3):.2f} GB")
print(f"Used: {disk_usage.used / (1024 ** 3):.2f} GB")
print(f"Free: {disk_usage.free / (1024 ** 3):.2f} GB")
print(f"Usage: {disk_usage.percent}%")

获取网络信息

import psutil

# 获取网络接口列表
network_interfaces = psutil.net_if_addrs()
for interface, addresses in network_interfaces.items():
    print(f"Interface: {interface}")
    for address in addresses:
        print(f"  Family: {address.family}")
        print(f"  Address: {address.address}")
        print(f"  Netmask: {address.netmask}")
        print(f"  Broadcast: {address.broadcast}")
    print("")

管理进程

查询进程信息

import psutil

# 获取所有进程列表
all_processes = psutil.process_iter(attrs=['pid', 'name'])
for process in all_processes:
    print(f"Process ID: {process.info['pid']}, Name: {process.info['name']}")

# 根据进程名称查询进程
process_name = "python3"
process_list = [p.info for p in all_processes if p.info['name'] == process_name]
for process in process_list:
    print(f"Process ID: {process['pid']}, Name: {process['name']}")

创建新进程

import psutil
import subprocess

# 创建新进程
subprocess.Popen(["notepad.exe"])

# 检查进程是否存在
process_name = "notepad.exe"
is_running = any(process.info['name'] == process_name for process in psutil.process_iter(attrs=['name']))
print(f"{process_name} is running: {is_running}")

终止进程

import psutil

# 根据进程名称终止进程
process_name = "notepad.exe"
for process in psutil.process_iter(attrs=['name']):
    if process.info['name'] == process_name:
        process.terminate()
        print(f"Terminated {process_name}")

监控系统性能

监控CPU利用率

import psutil
import time

# 监控CPU利用率
for _ in range(5):
    cpu_percent = psutil.cpu_percent(interval=1)
    print(f"CPU Usage: {cpu_percent}%")
    time.sleep(1)

监控内存使用量

import psutil
import time

# 监控内存使用量
for _ in range(5):
    memory_usage = psutil.virtual_memory().percent
    print(f"Memory Usage: 1.15MB%")
    time.sleep(1)

监控磁盘IO

import psutil
import time

# 监控磁盘IO
for _ in range(5):
    disk_io = psutil.disk_io_counters()
    print(f"Read

 Count: {disk_io.read_count}")
    print(f"Write Count: {disk_io.write_count}")
    time.sleep(1)

监控网络流量

import psutil
import time

# 监控网络流量
for _ in range(5):
    network_io = psutil.net_io_counters()
    print(f"Bytes Sent: {network_io.bytes_sent} bytes")
    print(f"Bytes Received: {network_io.bytes_recv} bytes")
    time.sleep(1)

操作系统资源

获取用户信息

import psutil

# 获取当前用户信息
user_info = psutil.users()
for user in user_info:
    print(f"User: {user.name}")
    print(f"Terminal: {user.terminal}")
    print(f"Host: {user.host}")
    print("")

获取虚拟内存信息

import psutil

# 获取虚拟内存信息
virtual_memory = psutil.virtual_memory()
print(f"Total: {virtual_memory.total / (1024 ** 3):.2f} GB")
print(f"Used: {virtual_memory.used / (1024 ** 3):.2f} GB")
print(f"Free: {virtual_memory.free / (1024 ** 3):.2f} GB")
print(f"Usage: {virtual_memory.percent}%")

安全性和权限考虑

在使用psutil库时,需要注意安全性和权限问题。某些功能可能需要管理员权限或超级用户权限才能访问,例如终止进程、查询其他用户的进程等。确保你的程序以合适的权限运行,以避免潜在的问题。

总结

psutil库是Python中用于系统监控和管理的强大工具,它提供了丰富的功能来获取系统信息、管理进程、监控系统性能等。本文介绍了psutil库的基本用法和示例代码,帮助大家更好地理解和利用这个库。无论是用于系统管理、性能监控、自动化任务还是系统信息收集,psutil都是一个不可或缺的Python神器。

以上就是Python利用psutil库进行监控进程和资源的详细内容,更多关于Python psutil的资料请关注脚本之家其它相关文章!

相关文章

  • Pandas中数据离散化的实现

    Pandas中数据离散化的实现

    Pandas中数据离散化是将连续变量转换为离散类别的过程,本文就来介绍一下Pandas中数据离散化的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-12-12
  • asyncio异步编程之Task对象详解

    asyncio异步编程之Task对象详解

    这篇文章主要为大家详细介绍了asyncio异步编程之Task对象,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2022-03-03
  • Python flask框架实现查询数据库并显示数据

    Python flask框架实现查询数据库并显示数据

    这篇文章主要介绍了Python flask框架实现查询数据库并显示数据,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-06-06
  • tensorflow模型转ncnn的操作方式

    tensorflow模型转ncnn的操作方式

    这篇文章主要介绍了tensorflow模型转ncnn的操作方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-05-05
  • Python实现图片转字符画的示例代码

    Python实现图片转字符画的示例代码

    本篇文章主要介绍了Python实现图片转字符画的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-08-08
  • urllib和BeautifulSoup爬取维基百科的词条简单实例

    urllib和BeautifulSoup爬取维基百科的词条简单实例

    这篇文章主要介绍了urllib和BeautifulSoup爬取维基百科的词条简单实例,具有一定借鉴价值,需要的朋友可以参考下
    2018-01-01
  • python使用电子邮件模块smtplib的方法

    python使用电子邮件模块smtplib的方法

    这篇文章主要介绍了python使用电子邮件模块smtplib的方法,需要的朋友可以参考下
    2016-08-08
  • python的xpath获取div标签内html内容,实现innerhtml功能的方法

    python的xpath获取div标签内html内容,实现innerhtml功能的方法

    今天小编就为大家分享一篇python的xpath获取div标签内html内容,实现innerhtml功能的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-01-01
  • Python类的基本写法与注释风格介绍

    Python类的基本写法与注释风格介绍

    这篇文章主要介绍了Python类的基本写法与注释风格,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-06-06
  • python和opencv构建运动检测器的实现

    python和opencv构建运动检测器的实现

    这篇文章主要介绍了python和opencv构建运动检测器的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-03-03

最新评论