I am writing code with python that might run wild and do unexpected things. These might include trying to save very large arrays to disk and trying to allocate huge amounts of memory for arrays (more than is physically available on the system).
I want to run the code in a constrained environment in Mac OSX 10.7.5 with the following rules:
Does anyone have any ideas on how to set up such a controlled environment?
Thanks.
import os
stats = os.stat('possibly_big_file.txt')
if (stats.st_size > TOOBIG):
print "Oh no....."
A simple and naive solution, that can be expanded to achieve what you want:
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)
Then, instead using the built-in open
you call my_open
. The same can be done for the arrays. Instead of allocating the arrays directly you call a function that keeps track of how much memory has been allocated and eventually raises an exception.
Obviously this gives only really light constraints, but if the program wasn't written with the goal of causing problems it should be enough.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.