Embedding python code into text document question.

tezlo tezlo at gmx.net
Thu Jan 10 09:27:17 EST 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 :)

Hi,
first, to quote the manual [1]
> 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 [2], or you
parse the whole template into one big python chunk, and exec that [3].

[1] http://docs.python.org/ref/exec.html
[2] http://blog.ianbicking.org/templating-via-dict-wrappers.html
[3] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/464766



More information about the Python-list mailing list