Embedding python code into text document question.
tezlo at gmx.net
Thu Jan 10 15:27:17 CET 2008
Thomas Troeger <thomas.troeger.ext at siemens.com> wrote:
> I've written a program that parses a string or file for embedded
> python commands, executes them and fills in the returned value.
> I've tried several solutions using eval, execfile or compile, but
> none of those would solve my problem. Does anyone have a solution
> that works? Any suggestions? Any help will be appreciated :)
first, to quote the manual 
> Be aware that the return and yield statements may not be used
> outside of function definitions even within the context of code
> passed to the exec statement.
Once you get rid of those return statements, the first two
substitutions could simpy be eval'ed. Conditions and loops can be
exec'ed, but you need to capture the output somehow. You could
replace sys.stdout with your own StringIO before you exec, and
use 'print' instead of 'return' in your templates.
Two basic approaches: you eval every substitution by itself , or you
parse the whole template into one big python chunk, and exec that .
More information about the Python-list