Evaluting a python code in a string

Alex Martelli aleaxit at yahoo.com
Fri Jan 19 12:20:59 EST 2001


"Steve Tuckner" <sat at multitech.com> wrote in message
news:Se_96.394$mY4.179630 at news.uswest.net...
> In Perl you can evaluation perl code that is embedded in a string by using
> the Eval function. For example the following code:
>
> $i = "hello"
> eval "print $i";
>
> will print "hello" to the terminal.
>
> How can a person do a similar function in Python?

To execute a statement held in a string:

i = 'hello'
exec 'print %s' % i

> I tried the following code:
>
> import code
> c = code.compile_command("print \"hello\"")
> code.runcode(c)
>
> and I get a run-time exception: Attribute error: runcode. I get the same
> error if instead I just use the runsource() function.

compile_command returns a code-object; I'm not sure where you
got the idea that a code-object has either a runcode or a runsource
method.

If you wish, you can use a code-object as a parameter to the exec
statement -- saves having to re-parse a string each time.  But you
may as well get the code-object from the builtin compile function --
all code.compile_command is adding is heuristics to determine if
a command (entered interactively) is incomplete.

    c = compile('print "hello"', '<string>', 'exec')

and then

    exec c


Alex






More information about the Python-list mailing list