re module substitution confusion

Doug Farrell writeson at earthlink.net
Tue Jul 8 13:25:38 EDT 2003


Hi all,

I got a direct email from someone (who I can't remember right now) who
suggested that I wasn't very clear about what I was trying to do and
what was wrong. In an attempt to clarify I'm adding this post. :)

I'm trying to create a little Python CGI program that will read in a
HTML template file that has Python code embedded in it between
<python> ... </python> tags. So I'd like to use the re module to find
the following pattern:

pattern = re.compile("(<python>)(.*?)(</python>)", re.DOTALL)

Doing a search with this pattern like this:

match = re.search(pattern, text)

where text equals the HTML template file in string form, will find all
the code segments. I then pull out the code segment and pass it to
exec() to execute it. I can capture the output of the exec() call by
redirecting sys.stdout to a StringIO object. The problem is that this;
I can match the <python>...</python> segments no problem. But I only
want to replace each one in turn with the results of the exec() call.
If I do this:

text = re.sub(pattern, ".. exec() output..", text) it replaces all the
code segments, not just the one that was matched. I need to substitute
in the output of the exec() (which is a string when I'm done) into the
one place it came from.

Hope this clears up any confusion.

I didn't include the whole program in my first post as it's kind of
long. I thought the sections I included above were enough information
to follow what I'm trying to do, at least I hope so.

Thanks again in advance for your help,
Doug




More information about the Python-list mailing list