How to access object attributes given a string
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Wed Feb 13 18:30:49 EST 2008
En Tue, 12 Feb 2008 18:53:36 -0200, Santiago Romero <sromero at gmail.com>
escribió:
>> Dennis Kempin wrote:
>> You are using a scripting language.. why not use python directly?
>
> I just want to execute an small set of commands (PLAYSOUND, PLAYMUSIC,
> WALKTO, PLAYERSAY, SLEEP and a couple more) ... do you think I can
> write python code inside my object.exec (list attribute) loaded from a
> file?
> Do you mean that I can replace my "language" by just python (defining
> SETMAP, SLEEP and all those functions somewhere in my main source
> code).
Something like that.
Build a dictionary -that will be used as the script global namespace-
containing all the required functions, plus a '__builtins__' entry
(another dict) containing the builtins that you want to provide. For
example, if you don't want to enable "import", don't include __import__.
import __builtin__
builtins = dict(__builtin__.__dict__) # a copy of the standard __builtin__
module namespace
del builtins['__import__']
ns = {
'SETMAP': SETMAP,
'SHOWTEXT': SHOWTEXT,
...
'__builtins__': builtins
}
exec text_of_the_user_script in ns
Warning: this is unsafe!!!. Malicious users could execute arbitrary code;
although this may not be an issue if the game runs on the user's own
system.
The advantage is that you let them use all the power of Python as a
scripting language.
--
Gabriel Genellina
More information about the Python-list
mailing list