python 3.4以后StringIO和cStringIO就没有了,转移到 io,的StringIO和BytesIO
from io import StringIO
fp=StringIO( )
1.StringIO模块
StringIO用于像文件一样对字符串缓冲区或者叫做内存文件进行读写。
f = StringIO() # ready for writing
f = StringIO(buf) # ready for reading
f.close() # explicitly release resources held
flag = f.isatty() # always false
pos = f.tell() # get current position
f.seek(pos) # set current position
f.seek(pos, mode) # mode 0: absolute; 1: relative; 2: relative to EOF
buf = f.read() # read until EOF
buf = f.read(n) # read up to n bytes
buf = f.readline() # read until end of line (‘\n‘) or EOF
list = f.readlines()# list of f.readline() results until EOF
f.truncate([size]) # truncate file at to at most size (default: current pos)
f.write(buf) # write at current position
f.writelines(list) # for line in list: f.write(line)
f.getvalue() # return whole file‘s contents as a string
在有些时候python调用shell命令或者使用socket向端口发送命令后返回一大串分行的字符串。就可以使用StringIO对这些字符串分行读写。
例如向ZooKeeper的端口发送mntr命令
import socket
s=socket.socket()
s.connect((‘localhost‘,2181))
s.send(‘mntr‘)
data_mntr=s.recv(2048)
s.close()
print data_mntr
# python test.py
zk_version3.4.6-1569965, built on 02/20/2014 09:09 GMT
zk_avg_latency0
zk_max_latency0
zk_min_latency0
zk_packets_received335
zk_packets_sent334
zk_num_alive_connections1
zk_outstanding_requests0
zk_server_statefollower
zk_znode_count17159
zk_watch_count0
zk_ephemerals_count1
zk_approximate_data_size6666471
zk_open_file_descriptor_count27
zk_max_file_descriptor_count102400
data_mntr返回的数据就是一个string buffer,如果需要对每行数据进行读写,就需要像文件那样使用readline()或者readlines()
#!/usr/bin/python
import socket
from StringIO import StringIO
s=socket.socket()
s.connect((‘localhost‘,2181))
s.send(‘mntr‘)
data_mntr=s.recv(2048)
s.close()
h=StringIO(data_mntr)
print h.readline()
print h.readlines()
# python test.py
zk_version3.4.6-1569965, built on 02/20/2014 09:09 GMT
[‘zk_avg_latency\t0\n‘, ‘zk_max_latency\t0\n‘, ‘zk_min_latency\t0\n‘, ‘zk_packets_received\t347\n‘, ‘zk_packets_sent\t346\n‘, ‘zk_num_alive_connections\t1\n‘, ‘zk_outstanding_requests\t0\n‘, ‘zk_server_state\tfollower\n‘, ‘zk_znode_count\t17159\n‘, ‘zk_watch_count\t0\n‘, ‘zk_ephemerals_count\t1\n‘, ‘zk_approximate_data_size\t6666471\n‘, ‘zk_open_file_descriptor_count\t27\n‘, ‘zk_max_file_descriptor_count\t102400\n‘]
2.cStringIO模块
cStringIO模块和StringIO模块功能类似。不过这个模块是用C语言编写的。
将以上的
from StringIO import StringIO
直接换成
from cStringIO import StringIO