injecting functions into a python sandbox within a python program

Graham Menhennitt gmenhennitt at optusnet.com.au
Tue Jan 9 17:29:06 EST 2007


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.

I've tried defining the helper funcions in my caller and passing them 
through the globals i.e.

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

The problem here is that the functions don't have access to the global 
variable 'i'. I need to use that object instance since it has other 
functionality that is required to interface to the rest of the program.

I'm sure that this is simple to get around for a Python expert (which I 
am not!). Does anybody have any ideas? Any alternate approach?

Thanks in advance for any assistance,
	Graham



More information about the Python-list mailing list