How to eval some code with in python

Alex Martelli aleaxit at yahoo.com
Sat Sep 9 18:51:22 EDT 2000


"Sindh" <skodela at my-deja.com> wrote in message
news:8pe2o4$9j2$1 at nnrp1.deja.com...
    [snip]
> How do you eval some python code during execution.

You _eval_ (an expression) with eval, or _exec_ (statements)
with exec.  The former gives you a result, the latter doesn't
(exec is a statement, while eval is a builtin function).

> class a:
> segmenta="print 3"
> segmentb='print "ok"'
> segmentc='raise SystemExit'
> ... etc

Note that these various segmenta, etc, are all statements.


> then from python
>
> codec=a()
> eval(codec.segmenta)
> ....
>
> Obviously it isn't working since it says 'syntax error'.

Use

    exec codec.segmenta

and it should work.


> Any idea what I'm doing wrong!

In Python, statements and expressions are very different
beasts.  You have to know which kind you're dealing with.


Alex






More information about the Python-list mailing list