Python:设置特定函数调用的内存限制 [英] Python: setting memory limit for a particular function call

查看:177
本文介绍了Python:设置特定函数调用的内存限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python脚本中,我想为某个函数调用设置内存限制.我查看了如何限制堆大小;但是,我不想限制整个正在运行的Python进程的内存-即在函数调用之前和之后设置内存限制.

In a Python script, I want to set a memory limit for a certain function call. I looked at how to limit heap size; however, I don't want to limit the memory of the entire running Python process -- i.e. setting the memory limit before and after the function call.

是否可以通过给定的内存量进行函数调用,以使内存限制不影响调用方?

Is there any way to make a function call with a given amount of memory, so that the memory limit doesn't affect the caller?

推荐答案

否,这是不可能的. Python不会跟踪哪些函数负责分配新的内存,而libc也不会跟踪,因此无法仅通过单个函数来限制内存使用.

No, this is impossible. Python doesn't keep track of which functions are responsible for allocating new memory, and nor does libc, so there's no way to limit memory usage just by a single function.

为此,您必须修改Python,以便使用新的函数分配内存,该函数要求指定由Python函数负责的函数,以便在该函数超出其内存分配范围时可以拒绝内存分配.限制.

In order to do this you would have to modify Python so that you use a new function for allocating memory that requires it to be specified what Python function is responsible, so that it can reject the memory allocation if that function goes over its limit.

执行此操作的唯一另一种方法确实是在一个内存有限的单独进程中执行该功能,如@JBernardo所说.

The only other way to do this would indeed be to execute the function in a separate process with limited memory, as @JBernardo said.

对于实现沙箱,已经有相对良好测试的实现.有什么原因不能使用这些吗?特别是请参阅PyPy的沙盒虚拟机

As for implementing sandboxes, there already are relatively well tested implementations. Is there any reason you can't use those? In particular see PyPy's sandboxed VM and the Zope sandbox.

这篇关于Python:设置特定函数调用的内存限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆