injecting functions into a python sandbox within a python program

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Tue Jan 9 18:19:35 EST 2007


Graham Menhennitt a écrit :
> I have a large Python 2.5 program that I want my users to be able to 
> "extend" using a Python script. However, I want their script to run in a 
> sandbox within the overall program so that they only have access to the 
> rest of the program via a single simple interface. Note that this is not 
> meant to be a real anti-hacker type security sandbox - just "help them 
> to avoid shooting themselves in the foot" type security.
> 
> So I created a single object that has the interface that I want them to 
> access. I call their script via "exec" passing the single interface 
> object in the "globals" parameter to exec. It (conceptually) looks like 
> this:
> 
> i = Interface()
> glob = { 'i': i }
> exec script in glob
> 
> Then they can call i.whatever() from within their script. This all works 
> fine.
> 
> Now, what I want to do is provide some "helper" functions for them to 
> use in the script. These functions still only access the rest of the 
> program via 'i'. They just wrap some of the interface functions to make 
> life easier for the user. My current solution is to prepend these 
> functions onto the start of the script. I.e.
> 
> helperFuncs = """
> def f1(): i.whatever()
> """
> 
> exec helperFuncs + "\n" + script.read() in glob
> 
> This works but doesn't seem very elegant.

Indeed.


If all your helper functions are really methods of the Interface 
instance, you may try this instead (NB : not tested):

glob = {
   'i': i,
   'f1': i.whatever,
}
exec script in glob

HTH



More information about the Python-list mailing list