Embedding python code into text document question.

MRAB google at mrabarnett.plus.com
Thu Jan 10 15:52:21 EST 2008


On Jan 10, 1:10 pm, Thomas Troeger <thomas.troeger.... at siemens.com>
wrote:
> Dear all,
>
> I've written a program that parses a string or file for embedded python
> commands, executes them and fills in the returned value. The input might
> look like this:
>
> process id: $$return os.getpid()$$
> current date: $$return time.ctime()$$
> superuser: $$
> if os.geteuid():
>         return "Yes"
> else:
>         return "No"$$
>
> 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 :)
>
You could wrap the bits of code in a def statement and then exec it:

>>> print field
return os.getpid()
>>> exec("def field_func():\n" + "".join("    %s\n" % line for line in field.splitlines()))
>>> print field_func()
3904



More information about the Python-list mailing list