[英]Can I limit write access of a program to a certain directory in osx? Also set maximum size of the directory and memory allocated
I am writing code with python that might run wild and do unexpected things. 我正在用python编写代码,这些代码可能会疯狂运行并做意外的事情。 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: 我想使用以下规则在Mac OSX 10.7.5的受限环境中运行代码:
Does anyone have any ideas on how to set up such a controlled environment? 有没有人对如何建立这样一个受控环境有任何想法?
Thanks. 谢谢。
import os 导入操作系统
stats = os.stat('possibly_big_file.txt') stats = os.stat('possfully_big_file.txt')
if (stats.st_size > TOOBIG): 如果(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
. 然后,而不是使用内置的open
您可以调用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. 显然,这只给了很小的限制,但是如果程序不是以引起问题为目标而编写的,那就足够了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.