Executing other python code

Arnaud Delobelle arnodel at googlemail.com
Tue Jan 29 08:26:25 EST 2008


On Jan 29, 12:18 am, Tim Rau <bladedpeng... at gmail.com> wrote:
> I'm working on a game, and I'd like players to be able to define thier
> ships with scripts. Naturally, I don't want to give them the entire
> program as thier romping ground. I would like to invoke a seperate
> interpreter for these files, and give it a limited subset of the
> functions in my game. What is the best way to achieve this effect?

One simple solution would be to forbid import statements in the
scripts, to import the scripts as modules and inject whatever
functions you want them to be able to use in the module's namespace.

So:

====== script.py =======

def play():
    if enemy_is_near():
        fire_gun()
    else:
        move_forward()

=======================

====== Game engine ====

scriptobjs = [enemy_is_near, fire_gun, move_forward, turn_left,
turn_right]

def getscript(scriptname):
    script = __import__(scriptname)
    for obj in scriptobjs:
        setattr(script, obj.__name__, obj)
    return script

def playscript(script):
    script.play()

=======================

Something like this.  Obviously this is over simplified!

--
Arnaud



More information about the Python-list mailing list