[英]Limit Python VM memory
我正在嘗試找到一種方法來限制Python VM可用的內存,就像Java VM中的選項“ -Xmx”一樣。 (這個想法是為了能夠處理MemoryError異常)
我不確定該選項是否存在,但是可能存在使用操作系統命令“隔離”進程及其內存的解決方案。
謝謝。
在Linux上,我正在使用資源模塊:
import resource
resource.setrlimit(resource.RLIMIT_AS, (megs * 1048576L, -1L))
在* nix上,您可以使用ulimit
命令,特別是-m(最大內存大小)和-v(虛擬內存)。
不要在此浪費任何時間。
相反,如果要使用MemoryError
異常,請創建一個隔離對象構造的設計,以便對其進行測試。
代替這個
for i in range(1000000000000000000000):
try:
y = AnotherClass()
except MemoryError:
# the thing we wanted to test
考慮一下。
for i in range(1000000000000000000000):
try:
y = makeAnotherClass()
except MemoryError:
# the thing we wanted to test
這需要對設計進行一點補充。
class AnotherClass( object ):
def __init__( self, *args, **kw ):
blah blah blah
def makeAnotherClass( *args, **kw ):
return AnotherClass( *args, **kw )
從長遠來看,額外的功能被證明是一種很好的設計模式。 這是一個Factory ,您經常需要類似的東西。
然后,您可以將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 )
此版本將引發異常,而您不必以任何晦澀,無法支持,復雜或不可思議的方式限制內存。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.