限制 Python VM 内存
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1760025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Limit Python VM memory
提问by Joril
I'm trying to find a way to limit the memory available for the Python VM, as the option "-Xmx" in the Java VM does. (The idea is to be able to play with the MemoryError exception)
我试图找到一种方法来限制 Python VM 的可用内存,就像 Java VM 中的选项“-Xmx”所做的那样。(这个想法是为了能够处理 MemoryError 异常)
I'm not sure this option exist but there may be a solution using a command of the OS to "isolate" a process and its memory.
我不确定此选项是否存在,但可能存在使用操作系统命令来“隔离”进程及其内存的解决方案。
Thank you.
谢谢你。
采纳答案by mhawke
On *nix you can play around with the ulimit
command, specifically the -m (max memory size) and -v (virtual memory).
在 *nix 上,您可以使用该ulimit
命令,特别是 -m(最大内存大小)和 -v(虚拟内存)。
回答by Joril
回答by S.Lott
Don't waste any time on this.
不要在这上面浪费任何时间。
Instead, if you want to play with MemoryError
exceptions create a design that isolates object construction so you can test it.
相反,如果您想处理MemoryError
异常,请创建一个隔离对象构造的设计,以便您可以对其进行测试。
Instead of this
而不是这个
for i in range(1000000000000000000000):
try:
y = AnotherClass()
except MemoryError:
# the thing we wanted to test
Consider this.
考虑一下。
for i in range(1000000000000000000000):
try:
y = makeAnotherClass()
except MemoryError:
# the thing we wanted to test
This requires one tiny addition to your design.
这需要在您的设计中添加一个小细节。
class AnotherClass( object ):
def __init__( self, *args, **kw ):
blah blah blah
def makeAnotherClass( *args, **kw ):
return AnotherClass( *args, **kw )
The extra function -- in the long run -- proves to be a good design pattern. It's a Factory, and you often need something like it.
从长远来看,额外的功能被证明是一种很好的设计模式。这是一个Factory,你经常需要类似的东西。
You can then replace this makeAnotherClass
with something like this.
然后你可以用这样makeAnotherClass
的东西替换它。
class Maker( object ):
def __init__( self, count= 12 ):
self.count= count
def __call__( self, *args, **kw ):
if self.count == 0:
raise MemoryError
self.count -= 1
return AnotherClass( *args, **kw )
makeAnotherClass= Maker( count=12 )
This version will raise an exception without you having to limit memory in any obscure, unsupportable, complex or magical way.
此版本将引发异常,而无需您以任何晦涩、无法支持、复杂或神奇的方式限制内存。