Python: setting memory limit for a particular function call

允我心安 提交于 2019-12-21 09:18:03

问题


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?


回答1:


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.

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.

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

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.



来源:https://stackoverflow.com/questions/10269974/python-setting-memory-limit-for-a-particular-function-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!