• 【python学习】基础篇-常用第三方库-psutil:用于获取CPU、磁盘与网络等系统信息和进程管理


    psutil是一个跨平台的Python库,用于获取系统信息和进程管理。以下是一些基本的用法:

    1. 获取CPU使用率
    cpu_percent = psutil.cpu_percent(interval=1)
    print(cpu_percent)
    
    
    • 1
    • 2
    • 3
    1. 获取内存使用情况
    memory_info = psutil.virtual_memory()
    print(memory_info.percent)
    
    
    • 1
    • 2
    • 3
    1. 获取磁盘使用情况
    disk_usage = psutil.disk_usage('/')
    print(disk_usage.percent)
    
    • 1
    • 2
    1. 获取所有进程ID
    all_pids = psutil.pids()
    print(all_pids)
    
    • 1
    • 2
    1. 获取指定进程信息
    pid = 1234
    process = psutil.Process(pid)
    print(process.name())
    print(process.status())
    
    • 1
    • 2
    • 3
    • 4
    1. 终止指定进程
    pid = 1234
    process = psutil.Process(pid)
    process.terminate()
    
    • 1
    • 2
    • 3
    1. 获取网络连接信息
    import psutil
    
    # 获取所有网络连接信息
    connections = psutil.net_connections()
    print(connections)
    
    # 获取指定网络连接信息
    connection = connections[0]
    print(connection)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    1. 获取网络接口信息
    import psutil
    
    # 获取所有网络接口信息
    interfaces = psutil.net_if_addrs()
    print(interfaces)
    
    # 获取指定网络接口信息
    interface = interfaces['eth0']
    print(interface)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    1. 获取网络流量信息
    import psutil
    
    # 获取当前进程的网络流量信息
    process = psutil.Process()
    net_io_counters = process.net_io_counters()
    print(net_io_counters)
    
    # 获取指定进程的网络流量信息
    pid = 1234
    process = psutil.Process(pid)
    net_io_counters = process.net_io_counters()
    print(net_io_counters)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    1. 获取网络连接状态信息
    import psutil
    
    # 获取所有网络连接状态信息
    connections = psutil.net_connections()
    for connection in connections:
        print(connection.status)
    
    # 获取指定网络连接状态信息
    connection = connections[0]
    print(connection.status)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
  • 相关阅读:
    2022年,软件测试已经不吃香了吗?
    C语言预处理
    【python】PySide中QMessageBox设置中文按钮及使用
    分解质因数——AcWing 197. 阶乘分解
    Redis 面试题汇总(不定期更新)
    vim的使用以及配置
    SpringMvc中的@RequestMapping的用法简介说明
    java+jsp基于ssm矿场仓储管理系统-计算机毕业设计
    ⑮、企业快速开发平台Spring Cloud之HTML 速查列表
    React请求机制优化思路
  • 原文地址:https://blog.csdn.net/weixin_42133116/article/details/134555892