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?

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值