eval vs. exec
holger krekel
pyth at devel.trillke.net
Mon May 27 12:15:15 EDT 2002
Simon Budig wrote:
> I want to execute things like the three following strings:
>
> "a = 2" ---> returns nothing
> "3 * 4" ---> returns 12
> "a=2; b=3; a*b" ---> returns 6
> My current code looks like this:
what you can do is e.g.
def run_code(string, mathstuff={'myabs': lambda x: abs(x)}):
import code
interpreter = code.InteractiveInterpreter()
interpreter.locals = mathstuff
codeobj = interpreter.compile(string)
result = interpreter.runcode(codeobj)
return result
run_code('a=2')
run_code('3*4')
run_code('a=2;b=3;a*b')
run_code('a=-3;myabs(a*5)')
(you should be able to paste it to your interpreter).
Is this what you want? You may need to fiddle around,
of course.
have fun,
holger
More information about the Python-list
mailing list