-------------------------------------------------------------------------------------
StringIO 模块的使用. 它实现了一个工作在内存的文件对象 (内存文件).
在大多需要标准文件对象的地方都可以使用它来替换.
-------------------------------------------------------------------------------------
使用 StringIO 模块从内存文件读入内容
-------------------------------------------------------------------------------------
import StringIO
MESSAGE = "abcdefg"
file = StringIO.StringIO(MESSAGE) # 将MESSAGE内容写入到内存中,并返回file类型到file变量
print file.read() # 读取内存文件内容
-------------------------------------------------------------------------------------
使用 StringIO 模块向内存文件写入内容
StringIO 类实现了内建文件对象的所有方法, 此外还有 getvalue 方法用来返回它内部的字符串值
-------------------------------------------------------------------------------------
file = StringIO.StringIO()
file.write("This man is no ordinary man. ") # 将内容写入到内存
file.write("This is Mr. F. G. Superman.") # 将内容写入到内存
print file.getvalue() # 输出file内存内容
-------------------------------------------------------------------------------------
使用 StringIO 模块捕获输出
StringIO 可以用于重新定向 Python 解释器的输出
-------------------------------------------------------------------------------------
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
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
cStringIO 模块
cStringIO 是一个可选的模块, 是 StringIO 的更快速实现. 它的工作方式和 StringIO 基本相同, 但是它不可以被继承
-------------------------------------------------------------------------------------
使用 cStringIO 模块
-------------------------------------------------------------------------------------
import cStringIO
MESSAGE = "That man is depriving a village somewhere of a computer scientist."
file = cStringIO.StringIO(MESSAGE)
print file.read()
That man is depriving a village somewhere of a computer scientist.
-------------------------------------------------------------------------------------
后退至 StringIO
为了让你的代码尽可能快, 但同时保证兼容低版本的 Python ,你可以使用一个小技巧在 cStringIO 不可用时启用 StringIO 模块
-------------------------------------------------------------------------------------
try:
import cStringIO
StringIO = cStringIO
except ImportError:
import StringIO
-------------------------------------------------------------------------------------