Python中利用resource模块限制CPU与内存使用及Windows资源查询

Alice
Alice
发布时间:2026-10-16 | 4人浏览过
原创

本文介绍如何在Linux系统中使用Python的resource模块限制进程的CPU时间和内存大小。通过设置RLIMIT_CPU和RLIMIT_AS,程序超时会触发SIGXCPU信号退出,内存不足则抛出MemoryError。此外,还提供了在Windows环境下通过wmic命令查询CPU和内存使用率的代码示例。

给内存和cpu使用量设置限制

在Linux操作系统中,若需通过Python对进程的内存和CPU使用量施加限制,可借助内置的resource模块实现。

相关文档参考地址:resource — Resource usage information

以下示例展示了如何限制Python进程的CPU使用时间。

import signal
import resource
import os
def time_exceeded(signo, frame):
    print("time's up")
    raise SystemExit(1)
def set_max_runtime(seconds):
    soft,hard = resource.getrlimit(resource.RLIMIT_CPU)
    resource.setrlimit(resource.RLIMIT_CPU, (seconds, hard))
    signal.signal(signal.SIGXCPU, time_exceeded)
if __name__ == '__main__':
    set_max_runtime(5)
    while True:
        pass

执行上述代码后,一旦超过设定的时间限制,系统将发送SIGXCPU信号。此时程序会执行清理操作并正常退出。

若需限制内存使用量,可调用如下函数进行配置。

def limit_memory(maxsize):
    soft, hard = resource.getrlimit(resource.RLIMIT_AS)
    resource.setrlimit(resource.RLIMIT_AS, (maxsize, hard))

设定内存上限后,若程序尝试分配更多内存且超出限制,Python将抛出MemoryError异常。

注:上述示例代码源自《Python Cookbook》第575页“给内存和cpu使用量设置限制”章节。

查询Windows系统的CPU及内存使用率

# -*- coding: UTF-8 -*-
import os
def get_info(metric):
    metric_cmd_map = {
        "cpu_usage_rate": "wmic cpu get loadpercentage",
        "mem_total": "wmic ComputerSystem get TotalPhysicalMemory",
        "mem_free": "wmic OS get FreePhysicalMemory"
    }
    out = os.popen("{}".format(metric_cmd_map.get(metric)))
    value = out.read().split("\n")[2]
    out.close()
    return float(value)
# cpu使用率
cpu_usage_rate = get_info('cpu_usage_rate')
print("windows的CPU使用率是{}%".format(cpu_usage_rate))
# 无法直接查出内存使用率,总内存单位是b,而剩余内存单位是kb
mem_total = get_info('mem_total')/1024
mem_free = get_info('mem_free')
mem_usage_rate = (1 - mem_free/mem_total)*100
print("windows的内存使用率是{}%".format(mem_usage_rate))

以上为个人经验分享,旨在提供参考,欢迎大家支持本站。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表