Exec Statement Question
Dave Angel
davea at ieee.org
Sun Nov 29 22:23:15 EST 2009
Victor Subervi wrote:
> Hi;
> I have the following line of code:
>
> exec('%s()' % table)
>
> where 'table' is a variable in a for loop that calls variables from another
> script. I've made it so that it only calls one variable. I know for a fact
> that it's calling that variable in the script because it found errors in
> that script. I've tried to have it return the following:
>
> print 'hi'
> return 'hi'
>
> It doesn't return anything. No errors are thrown because the code evaluates.
> I don't know how to capture the output. I would like to do something like:
>
> print exec(...)
>
> or
>
> var = exec(...)
>
> but of course those options don't work. Suggestions?
> TIA,
> Victor
>
>
exec is a statement, and statements don't have "return values." It's
not a function, so there are no parentheses in its syntax, either. exec
is also a technique of last resort; there's nearly always a
better/safer/faster way to accomplish what you might want, but of course
you don't say what that is.
As for "returning" values, exec by default uses the same global space as
your app, so you can just modify a global variable in your "called" code
and use it afterwards.
abc = 42
value = 12
exec "abc = %d" % value
print abc
DaveA
More information about the Python-list
mailing list