2011年11月4日 星期五

Python 模組:StringIO 將內存文件寫入內容與重導向

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




進階用法:
使用cStringIO效能較佳

你可以使用一個小技巧在 cStringIO 不可用時啟用 StringIO 模組


File: cstringio-example-2.py
try:
    import cStringIO
    StringIO = cStringIO
except ImportError:
    import StringIO
print StringIO

沒有留言:

張貼留言