Sending part of a page as the body of an email

Jesse Hager wrffruntre at tznvy.pbz.ROT13
Sun Apr 16 15:16:52 EDT 2006


Kun wrote:
> I currently have a python-cgi script that extracts data from a mysql 
> table.  I would like to save this data as a string and send it to a 
> recipient via email.
> 
> I know how to send email using the smtp lib, but what I do not know his 
> how to save a portion of the page as a string.  Any pointers?

#At the top of your CGI script import these
import sys
import StringIO

#Create a StringIO object to hold output
string_io = StringIO.StringIO()
#Save the old sys.stdout so we can go back to it later
old_stdout = sys.stdout

#Normal output goes here



#To start capturing output replace sys.stdout with the StringIO object
sys.stdout = string_io

#Captured output goes here

#To finish capturing
sys.stdout = old_stdout

#To get the captured text from the StringIO object do:
captured_text = string_io.getvalue()

#To output the captured text to the original sys.stdout
#If this is omitted, the captured_text will not be sent to the browser
old_stdout.write(captured_text)

#You can repeat this capturing section several times and the output
#will accumulate in the StringIO object. To clear the contents of the
#StringIO object between sections do:
#string_io.truncate(0)



#More normal output goes here
#Do whatever you want with captured_text here...


#When finished with string_io, close it to free up the memory buffers
string_io.close()


--
Jesse Hager
email = "wrffruntre at tznvy.pbz".decode("rot13")



More information about the Python-list mailing list