首页 技术 正文
技术 2022年11月14日
0 收藏 548 点赞 2,922 浏览 1085 个字

参考:http://pymotwcn.readthedocs.org/en/latest/documents/StringIO.html

类StringIO提供了一个在内存中方便处理文本的类文件(读, 写等操作)API. 使用cStringIO来处理大字符串可以提高运行性能,优于其他字符串串联技术.

E:使用StringIO缓冲

#!/usr/bin/env python"""
Simple examples with StringIO module
"""# Find the best implementation available on this platformtry:
from cStringIO import StringIO
except:
from StringIO import StringIO# Writing to a buffer
output = StringIO()
output.write('This goes into the buffer. ')print >>output, 'And so does this.'
# Retrieve the value written
print output.getvalue()output.close() # discard buffer memory# Initialize a read buffer
input = StringIO('Inital value for read buffer')# Read from the buffer
print input.read()

这个例子中使用了 read() , 但当然, 函数 readline() 和 readlines() 也都是可用的.类StringIO提供 seek() 函数, 因此在读取数据时可以任意跳到某个点上, 这也当你使用某些前看解析算法可以回头读取.

现实世界中, StringIO的应用包括一个网络应用程序栈, 栈的各个部分都可以增加文本到响应response对象中, 或者测试由程序某段输出(典型是写入到文件)的数据.

我们想在创建的工程应用中包括一个shell脚本接口, 他是以多个命令行程序的形式. 这些程序中的某些是负责从数据库中取数据, 然后将这些数据转储到控制台(可以是现实给用户, 也可以是文本中, 这样就可以作为另一个命令的输入). 这些命令他们共享了一组格式化插件以便产生一个对象的多种文本表示(XML, bash语法, 人可读的, 等等).

因为格式化可以将输出数据标准化后写到标准输出, 如果没有StringIO模块, 所得的测试结果可能会有些奇怪. 而使用了StringIO来拦截格式化的输出, 这样以便我们用一个简单的方式来收集内存中的输出数据, 来对预期的结果做比较.

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,088
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,564
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,412
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,185
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,822
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,905