The stringio
module shown in Example 2-8 implements an in-memory file object. This object can be
used as input or output to most functions that expect a standard file
object.
The StringIO class implements memory file versions of all
methods available for built-in file objects, plus a
getvalue
method that returns the internal string
value. Example 2-9 demonstrates this method.
StringIO
can be used to capture redirected
output from the Python interpreter, as shown in Example 2-10.
Example 2-10. Using the StringIO Module to Capture Output
File: stringio-example-3.py import StringIO import string, sys stdout = sys.stdout sys.stdout = file = StringIO.StringIO() print """ According to Gbaya folktales, trickery and guile are the best ways to defeat the python, king of snakes, which was hatched from a dragon at the world's start. -- National Geographic, May 1997 """ sys.stdout = stdout print string.upper(file.getvalue())ACCORDING TO GBAYA FOLKTALES, TRICKERY AND GUILE
ARE THE BEST WAYS TO DEFEAT THE PYTHON, KING OF
SNAKES, WHICH WAS HATCHED FROM A DRAGON AT THE
WORLD'S START. -- NATIONAL GEOGRAPHIC, MAY 1997
3.129.42.134