简体   繁体   English

Python:为特定函数调用设置内存限制

[英]Python: setting memory limit for a particular function call

In a Python script, I want to set a memory limit for a certain function call.在 Python 脚本中,我想为某个函数调用设置内存限制。 I looked at how to limit heap size ;我查看了如何限制堆大小 however, I don't want to limit the memory of the entire running Python process -- ie setting the memory limit before and after the function call.但是,我不想限制整个正在运行的 Python 进程的内存——即在函数调用之前和之后设置内存限制。

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?有没有办法用给定的内存量进行函数调用,这样内存限制就不会影响调用者?

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 不会跟踪哪些函数负责分配新内存,libc 也不会,因此无法仅通过单个函数来限制内存使用。

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.为了做到这一点,您必须修改 Python,以便您使用一个新函数来分配内存,该函数要求指定 Python 函数负责的内容,以便在该函数超出其限制时拒绝内存分配。

The only other way to do this would indeed be to execute the function in a separate process with limited memory, as @JBernardo said.正如@JBernardo 所说,唯一的另一种方法确实是在内存有限的单独进程中执行该函数。

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 .特别是请参阅 PyPy 的沙盒 VMZope 沙盒

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM