[英]Can I limit write access of a program to a certain directory in osx? Also set maximum size of the directory and memory allocated
我正在用python編寫代碼,這些代碼可能會瘋狂運行並做意外的事情。 這些可能包括嘗試將非常大的陣列保存到磁盤,並嘗試為陣列分配大量內存(超過系統上實際可用的內存)。
我想使用以下規則在Mac OSX 10.7.5的受限環境中運行代碼:
有沒有人對如何建立這樣一個受控環境有任何想法?
謝謝。
導入操作系統
stats = os.stat('possfully_big_file.txt')
如果(stats.st_size> TOOBIG):
打印“哦,不.....”
一個簡單而幼稚的解決方案,可以擴展以實現您想要的:
WRITABLE_DIRECTORY = '/full/path/to/writable/directory'
class MaxSizeFile(object):
def __init__(self, fobj, max_bytes=float('+inf')):
self._fobj = fobj
self._max = max_bytes
self._cur = 0
def write(self, data):
# should take into account file position...
if self._cur + len(data) > self._max:
raise IOError('The file is too big!')
self._fobj.write(data)
self._cur += len(data)
def __getattr__(self, attr):
return getattr(self._fobj, attr)
def my_open(filename, mode='r', ..., max_size=float('+inf')):
if '+' in mode or 'w' in mode:
if os.path.dirname(filename) != WRITABLE_DIRECTORY:
raise OSError('Cannot write outside the writable directory.')
return MaxSizeFile(open(filename, mode, ...), max_size)
然后,而不是使用內置的open
您可以調用my_open
。 可以對數組執行相同的操作。 而不是直接分配數組,而是調用一個函數,該函數跟蹤已分配了多少內存,並最終引發異常。
顯然,這只給了很小的限制,但是如果程序不是以引起問題為目標而編寫的,那就足夠了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.