限制Windows中的python脚本RAM使用率

时间:2019-03-01 16:55:18

标签: python windows resources ram ulimit

我的程序可以根据使用情况突然分配大量RAM。 我想限制它可以从系统获取的RAM。

我在这里看到: Limit RAM usage to python program

但是它仅适用于Unix。 Windows是否有解决方案?

2 个答案:

答案 0 :(得分:3)

Job object支持限制进程的提交内存。在Python中,我们可以通过PyWin32或ctypes来实现。

请注意,在Windows 8之前,一个进程只能在一个Job中。担心这两种常见情况包括:在作业中运行python.exe的py.exe启动器(.py文件的默认关联),以及在作业中运行每个任务的任务计划程序服务。 / p>

PyWin32示例

import sys
import warnings

import winerror
import win32api
import win32job

g_hjob = None

def create_job(job_name='', breakaway='silent'):
    hjob = win32job.CreateJobObject(None, job_name)
    if breakaway:
        info = win32job.QueryInformationJobObject(hjob,
                    win32job.JobObjectExtendedLimitInformation)
        if breakaway == 'silent':
            info['BasicLimitInformation']['LimitFlags'] |= (
                win32job.JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK)
        else:
            info['BasicLimitInformation']['LimitFlags'] |= (
                win32job.JOB_OBJECT_LIMIT_BREAKAWAY_OK)
        win32job.SetInformationJobObject(hjob,
            win32job.JobObjectExtendedLimitInformation, info)
    return hjob

def assign_job(hjob):
    global g_hjob
    hprocess = win32api.GetCurrentProcess()
    try:
        win32job.AssignProcessToJobObject(hjob, hprocess)
        g_hjob = hjob
    except win32job.error as e:
        if (e.winerror != winerror.ERROR_ACCESS_DENIED or
            sys.getwindowsversion() >= (6, 2) or
            not win32job.IsProcessInJob(hprocess, None)):
            raise
        warnings.warn('The process is already in a job. Nested jobs are not '
            'supported prior to Windows 8.')

def limit_memory(memory_limit):
    if g_hjob is None:
        return
    info = win32job.QueryInformationJobObject(g_hjob,
                win32job.JobObjectExtendedLimitInformation)
    info['ProcessMemoryLimit'] = memory_limit
    info['BasicLimitInformation']['LimitFlags'] |= (
        win32job.JOB_OBJECT_LIMIT_PROCESS_MEMORY)
    win32job.SetInformationJobObject(g_hjob,
        win32job.JobObjectExtendedLimitInformation, info)

def main():
    assign_job(create_job())
    memory_limit = 100 * 1024 * 1024 # 100 MiB
    limit_memory(memory_limit)
    try:
        bytearray(memory_limit)
    except MemoryError:
        print('Success: available memory is limited.')
    else:
        print('Failure: available memory is not limited.')
    return 0

if __name__ == '__main__':
    sys.exit(main())

答案 1 :(得分:0)

除了要限制使用的物理RAM数量(而不是虚拟内存)以外,我和OP大约有相同的问题。 @eryksun的答案和@objc func validate(){ var filteredArray = [textFieldOne,textFieldTwo,textFieldThree,textFieldFour].filter { $0?.text == "" } if !filteredArray.isEmpty { button.isHidden = true } else { button.isHidden = false } } 函数的效果很好,但是限制了可分配内存(虚拟内存)的总量。这是他/她的代码的附加功能,可限制物理内存量(“工作集”)。

limit_memory()