blob: e7c8e04fad5aad78df7666e9d9eee219bcb9dd46 [file] [log] [blame]
Guido van Rossum4acc25b2000-02-02 15:10:15 +00001"""File-like objects that read from or write to a string buffer.
2
3This implements (nearly) all stdio methods.
4
5f = StringIO() # ready for writing
6f = StringIO(buf) # ready for reading
7f.close() # explicitly release resources held
8flag = f.isatty() # always false
9pos = f.tell() # get current position
10f.seek(pos) # set current position
11f.seek(pos, mode) # mode 0: absolute; 1: relative; 2: relative to EOF
12buf = f.read() # read until EOF
13buf = f.read(n) # read up to n bytes
14buf = f.readline() # read until end of line ('\n') or EOF
15list = f.readlines()# list of f.readline() results until EOF
Fred Drakee0a7f4f2000-09-28 04:21:06 +000016f.truncate([size]) # truncate file at to at most size (default: current pos)
Guido van Rossum4acc25b2000-02-02 15:10:15 +000017f.write(buf) # write at current position
18f.writelines(list) # for line in list: f.write(line)
19f.getvalue() # return whole file's contents as a string
20
21Notes:
22- Using a real file is often faster (but less convenient).
Guido van Rossum98d9fd32000-02-28 15:12:25 +000023- There's also a much faster implementation in C, called cStringIO, but
24 it's not subclassable.
Guido van Rossum4acc25b2000-02-02 15:10:15 +000025- fileno() is left unimplemented so that code which uses it triggers
26 an exception early.
27- Seeking far beyond EOF and then writing will insert real null
28 bytes that occupy space in the buffer.
29- There's a simple test set (see end of this file).
30"""
Guido van Rossum85d89451994-06-23 11:53:27 +000031
Barry Warsawc7ed0e32000-12-12 23:12:23 +000032try:
Barry Warsawc1401312000-12-12 23:16:51 +000033 from errno import EINVAL
Barry Warsawc7ed0e32000-12-12 23:12:23 +000034except ImportError:
Barry Warsawc1401312000-12-12 23:16:51 +000035 EINVAL = 22
Barry Warsawc7ed0e32000-12-12 23:12:23 +000036
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000037__all__ = ["StringIO"]
38
Guido van Rossum85d89451994-06-23 11:53:27 +000039class StringIO:
Barry Warsawc1401312000-12-12 23:16:51 +000040 def __init__(self, buf = ''):
Marc-André Lemburge47df7a2001-09-24 17:34:52 +000041 # Force self.buf to be a string
42 self.buf = str(buf)
Fred Drakea63bd1c2000-12-13 20:23:11 +000043 self.len = len(buf)
44 self.buflist = []
45 self.pos = 0
46 self.closed = 0
47 self.softspace = 0
Barry Warsawc1401312000-12-12 23:16:51 +000048
Barry Warsawbdefa0b2001-09-22 04:34:54 +000049 def __iter__(self):
50 return iter(self.readline, '')
51
Barry Warsawc1401312000-12-12 23:16:51 +000052 def close(self):
Fred Drakea63bd1c2000-12-13 20:23:11 +000053 if not self.closed:
54 self.closed = 1
55 del self.buf, self.pos
Barry Warsawc1401312000-12-12 23:16:51 +000056
57 def isatty(self):
Fred Drakea63bd1c2000-12-13 20:23:11 +000058 if self.closed:
59 raise ValueError, "I/O operation on closed file"
60 return 0
Barry Warsawc1401312000-12-12 23:16:51 +000061
62 def seek(self, pos, mode = 0):
Fred Drakea63bd1c2000-12-13 20:23:11 +000063 if self.closed:
64 raise ValueError, "I/O operation on closed file"
65 if self.buflist:
Marc-André Lemburg85d6edf2001-02-09 13:37:37 +000066 self.buf += ''.join(self.buflist)
Fred Drakea63bd1c2000-12-13 20:23:11 +000067 self.buflist = []
68 if mode == 1:
69 pos += self.pos
70 elif mode == 2:
71 pos += self.len
72 self.pos = max(0, pos)
Barry Warsawc1401312000-12-12 23:16:51 +000073
74 def tell(self):
Fred Drakea63bd1c2000-12-13 20:23:11 +000075 if self.closed:
76 raise ValueError, "I/O operation on closed file"
77 return self.pos
Barry Warsawc1401312000-12-12 23:16:51 +000078
79 def read(self, n = -1):
Fred Drakea63bd1c2000-12-13 20:23:11 +000080 if self.closed:
81 raise ValueError, "I/O operation on closed file"
82 if self.buflist:
Marc-André Lemburg85d6edf2001-02-09 13:37:37 +000083 self.buf += ''.join(self.buflist)
Fred Drakea63bd1c2000-12-13 20:23:11 +000084 self.buflist = []
85 if n < 0:
86 newpos = self.len
87 else:
88 newpos = min(self.pos+n, self.len)
89 r = self.buf[self.pos:newpos]
90 self.pos = newpos
91 return r
Barry Warsawc1401312000-12-12 23:16:51 +000092
93 def readline(self, length=None):
Fred Drakea63bd1c2000-12-13 20:23:11 +000094 if self.closed:
95 raise ValueError, "I/O operation on closed file"
96 if self.buflist:
Marc-André Lemburg85d6edf2001-02-09 13:37:37 +000097 self.buf += ''.join(self.buflist)
Fred Drakea63bd1c2000-12-13 20:23:11 +000098 self.buflist = []
99 i = self.buf.find('\n', self.pos)
100 if i < 0:
101 newpos = self.len
102 else:
103 newpos = i+1
104 if length is not None:
105 if self.pos + length < newpos:
106 newpos = self.pos + length
107 r = self.buf[self.pos:newpos]
108 self.pos = newpos
109 return r
Barry Warsawc1401312000-12-12 23:16:51 +0000110
111 def readlines(self, sizehint = 0):
Fred Drakea63bd1c2000-12-13 20:23:11 +0000112 total = 0
113 lines = []
114 line = self.readline()
115 while line:
116 lines.append(line)
117 total += len(line)
118 if 0 < sizehint <= total:
119 break
120 line = self.readline()
121 return lines
Barry Warsawc1401312000-12-12 23:16:51 +0000122
123 def truncate(self, size=None):
Fred Drakea63bd1c2000-12-13 20:23:11 +0000124 if self.closed:
125 raise ValueError, "I/O operation on closed file"
126 if size is None:
127 size = self.pos
128 elif size < 0:
129 raise IOError(EINVAL, "Negative size not allowed")
130 elif size < self.pos:
131 self.pos = size
132 self.buf = self.getvalue()[:size]
Barry Warsawc1401312000-12-12 23:16:51 +0000133
134 def write(self, s):
Fred Drakea63bd1c2000-12-13 20:23:11 +0000135 if self.closed:
136 raise ValueError, "I/O operation on closed file"
137 if not s: return
Marc-André Lemburge47df7a2001-09-24 17:34:52 +0000138 # Force s to be a string
139 s = str(s)
Fred Drakea63bd1c2000-12-13 20:23:11 +0000140 if self.pos > self.len:
141 self.buflist.append('\0'*(self.pos - self.len))
142 self.len = self.pos
143 newpos = self.pos + len(s)
144 if self.pos < self.len:
145 if self.buflist:
Marc-André Lemburg85d6edf2001-02-09 13:37:37 +0000146 self.buf += ''.join(self.buflist)
Fred Drakea63bd1c2000-12-13 20:23:11 +0000147 self.buflist = []
148 self.buflist = [self.buf[:self.pos], s, self.buf[newpos:]]
149 self.buf = ''
150 if newpos > self.len:
151 self.len = newpos
152 else:
153 self.buflist.append(s)
154 self.len = newpos
155 self.pos = newpos
Barry Warsawc1401312000-12-12 23:16:51 +0000156
157 def writelines(self, list):
Marc-André Lemburg85d6edf2001-02-09 13:37:37 +0000158 self.write(''.join(list))
Barry Warsawc1401312000-12-12 23:16:51 +0000159
160 def flush(self):
Fred Drakea63bd1c2000-12-13 20:23:11 +0000161 if self.closed:
162 raise ValueError, "I/O operation on closed file"
Barry Warsawc1401312000-12-12 23:16:51 +0000163
164 def getvalue(self):
Fred Drakea63bd1c2000-12-13 20:23:11 +0000165 if self.buflist:
Marc-André Lemburg85d6edf2001-02-09 13:37:37 +0000166 self.buf += ''.join(self.buflist)
Fred Drakea63bd1c2000-12-13 20:23:11 +0000167 self.buflist = []
168 return self.buf
Guido van Rossum85d89451994-06-23 11:53:27 +0000169
170
171# A little test suite
172
173def test():
Barry Warsawc1401312000-12-12 23:16:51 +0000174 import sys
175 if sys.argv[1:]:
Fred Drakea63bd1c2000-12-13 20:23:11 +0000176 file = sys.argv[1]
Barry Warsawc1401312000-12-12 23:16:51 +0000177 else:
Fred Drakea63bd1c2000-12-13 20:23:11 +0000178 file = '/etc/passwd'
Barry Warsawc1401312000-12-12 23:16:51 +0000179 lines = open(file, 'r').readlines()
180 text = open(file, 'r').read()
181 f = StringIO()
182 for line in lines[:-2]:
Fred Drakea63bd1c2000-12-13 20:23:11 +0000183 f.write(line)
Barry Warsawc1401312000-12-12 23:16:51 +0000184 f.writelines(lines[-2:])
185 if f.getvalue() != text:
Fred Drakea63bd1c2000-12-13 20:23:11 +0000186 raise RuntimeError, 'write failed'
Barry Warsawc1401312000-12-12 23:16:51 +0000187 length = f.tell()
188 print 'File length =', length
189 f.seek(len(lines[0]))
190 f.write(lines[1])
191 f.seek(0)
192 print 'First line =', `f.readline()`
193 here = f.tell()
194 line = f.readline()
195 print 'Second line =', `line`
196 f.seek(-len(line), 1)
197 line2 = f.read(len(line))
198 if line != line2:
Fred Drakea63bd1c2000-12-13 20:23:11 +0000199 raise RuntimeError, 'bad result after seek back'
Barry Warsawc1401312000-12-12 23:16:51 +0000200 f.seek(len(line2), 1)
201 list = f.readlines()
202 line = list[-1]
203 f.seek(f.tell() - len(line))
204 line2 = f.read()
205 if line != line2:
Fred Drakea63bd1c2000-12-13 20:23:11 +0000206 raise RuntimeError, 'bad result after seek back from EOF'
Barry Warsawc1401312000-12-12 23:16:51 +0000207 print 'Read', len(list), 'more lines'
208 print 'File length =', f.tell()
209 if f.tell() != length:
Fred Drakea63bd1c2000-12-13 20:23:11 +0000210 raise RuntimeError, 'bad length'
Barry Warsawc1401312000-12-12 23:16:51 +0000211 f.close()
Guido van Rossum85d89451994-06-23 11:53:27 +0000212
213if __name__ == '__main__':
Barry Warsawc1401312000-12-12 23:16:51 +0000214 test()