blob: bc5e9e24327a5100d9e2bcde5bd7f0b424584cdc [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
Barry Warsawc7ed0e32000-12-12 23:12:23 +000039EMPTYSTRING = ''
Guido van Rossum85d89451994-06-23 11:53:27 +000040
41class StringIO:
Barry Warsawc1401312000-12-12 23:16:51 +000042 def __init__(self, buf = ''):
Fred Drakea63bd1c2000-12-13 20:23:11 +000043 self.buf = buf
44 self.len = len(buf)
45 self.buflist = []
46 self.pos = 0
47 self.closed = 0
48 self.softspace = 0
Barry Warsawc1401312000-12-12 23:16:51 +000049
50 def close(self):
Fred Drakea63bd1c2000-12-13 20:23:11 +000051 if not self.closed:
52 self.closed = 1
53 del self.buf, self.pos
Barry Warsawc1401312000-12-12 23:16:51 +000054
55 def isatty(self):
Fred Drakea63bd1c2000-12-13 20:23:11 +000056 if self.closed:
57 raise ValueError, "I/O operation on closed file"
58 return 0
Barry Warsawc1401312000-12-12 23:16:51 +000059
60 def seek(self, pos, mode = 0):
Fred Drakea63bd1c2000-12-13 20:23:11 +000061 if self.closed:
62 raise ValueError, "I/O operation on closed file"
63 if self.buflist:
64 self.buf += EMPTYSTRING.join(self.buflist)
65 self.buflist = []
66 if mode == 1:
67 pos += self.pos
68 elif mode == 2:
69 pos += self.len
70 self.pos = max(0, pos)
Barry Warsawc1401312000-12-12 23:16:51 +000071
72 def tell(self):
Fred Drakea63bd1c2000-12-13 20:23:11 +000073 if self.closed:
74 raise ValueError, "I/O operation on closed file"
75 return self.pos
Barry Warsawc1401312000-12-12 23:16:51 +000076
77 def read(self, n = -1):
Fred Drakea63bd1c2000-12-13 20:23:11 +000078 if self.closed:
79 raise ValueError, "I/O operation on closed file"
80 if self.buflist:
81 self.buf += EMPTYSTRING.join(self.buflist)
82 self.buflist = []
83 if n < 0:
84 newpos = self.len
85 else:
86 newpos = min(self.pos+n, self.len)
87 r = self.buf[self.pos:newpos]
88 self.pos = newpos
89 return r
Barry Warsawc1401312000-12-12 23:16:51 +000090
91 def readline(self, length=None):
Fred Drakea63bd1c2000-12-13 20:23:11 +000092 if self.closed:
93 raise ValueError, "I/O operation on closed file"
94 if self.buflist:
95 self.buf += EMPTYSTRING.join(self.buflist)
96 self.buflist = []
97 i = self.buf.find('\n', self.pos)
98 if i < 0:
99 newpos = self.len
100 else:
101 newpos = i+1
102 if length is not None:
103 if self.pos + length < newpos:
104 newpos = self.pos + length
105 r = self.buf[self.pos:newpos]
106 self.pos = newpos
107 return r
Barry Warsawc1401312000-12-12 23:16:51 +0000108
109 def readlines(self, sizehint = 0):
Fred Drakea63bd1c2000-12-13 20:23:11 +0000110 total = 0
111 lines = []
112 line = self.readline()
113 while line:
114 lines.append(line)
115 total += len(line)
116 if 0 < sizehint <= total:
117 break
118 line = self.readline()
119 return lines
Barry Warsawc1401312000-12-12 23:16:51 +0000120
121 def truncate(self, size=None):
Fred Drakea63bd1c2000-12-13 20:23:11 +0000122 if self.closed:
123 raise ValueError, "I/O operation on closed file"
124 if size is None:
125 size = self.pos
126 elif size < 0:
127 raise IOError(EINVAL, "Negative size not allowed")
128 elif size < self.pos:
129 self.pos = size
130 self.buf = self.getvalue()[:size]
Barry Warsawc1401312000-12-12 23:16:51 +0000131
132 def write(self, s):
Fred Drakea63bd1c2000-12-13 20:23:11 +0000133 if self.closed:
134 raise ValueError, "I/O operation on closed file"
135 if not s: return
136 if self.pos > self.len:
137 self.buflist.append('\0'*(self.pos - self.len))
138 self.len = self.pos
139 newpos = self.pos + len(s)
140 if self.pos < self.len:
141 if self.buflist:
142 self.buf += EMPTYSTRING.join(self.buflist)
143 self.buflist = []
144 self.buflist = [self.buf[:self.pos], s, self.buf[newpos:]]
145 self.buf = ''
146 if newpos > self.len:
147 self.len = newpos
148 else:
149 self.buflist.append(s)
150 self.len = newpos
151 self.pos = newpos
Barry Warsawc1401312000-12-12 23:16:51 +0000152
153 def writelines(self, list):
Fred Drakea63bd1c2000-12-13 20:23:11 +0000154 self.write(EMPTYSTRING.join(list))
Barry Warsawc1401312000-12-12 23:16:51 +0000155
156 def flush(self):
Fred Drakea63bd1c2000-12-13 20:23:11 +0000157 if self.closed:
158 raise ValueError, "I/O operation on closed file"
Barry Warsawc1401312000-12-12 23:16:51 +0000159
160 def getvalue(self):
Fred Drakea63bd1c2000-12-13 20:23:11 +0000161 if self.buflist:
162 self.buf += EMPTYSTRING.join(self.buflist)
163 self.buflist = []
164 return self.buf
Guido van Rossum85d89451994-06-23 11:53:27 +0000165
166
167# A little test suite
168
169def test():
Barry Warsawc1401312000-12-12 23:16:51 +0000170 import sys
171 if sys.argv[1:]:
Fred Drakea63bd1c2000-12-13 20:23:11 +0000172 file = sys.argv[1]
Barry Warsawc1401312000-12-12 23:16:51 +0000173 else:
Fred Drakea63bd1c2000-12-13 20:23:11 +0000174 file = '/etc/passwd'
Barry Warsawc1401312000-12-12 23:16:51 +0000175 lines = open(file, 'r').readlines()
176 text = open(file, 'r').read()
177 f = StringIO()
178 for line in lines[:-2]:
Fred Drakea63bd1c2000-12-13 20:23:11 +0000179 f.write(line)
Barry Warsawc1401312000-12-12 23:16:51 +0000180 f.writelines(lines[-2:])
181 if f.getvalue() != text:
Fred Drakea63bd1c2000-12-13 20:23:11 +0000182 raise RuntimeError, 'write failed'
Barry Warsawc1401312000-12-12 23:16:51 +0000183 length = f.tell()
184 print 'File length =', length
185 f.seek(len(lines[0]))
186 f.write(lines[1])
187 f.seek(0)
188 print 'First line =', `f.readline()`
189 here = f.tell()
190 line = f.readline()
191 print 'Second line =', `line`
192 f.seek(-len(line), 1)
193 line2 = f.read(len(line))
194 if line != line2:
Fred Drakea63bd1c2000-12-13 20:23:11 +0000195 raise RuntimeError, 'bad result after seek back'
Barry Warsawc1401312000-12-12 23:16:51 +0000196 f.seek(len(line2), 1)
197 list = f.readlines()
198 line = list[-1]
199 f.seek(f.tell() - len(line))
200 line2 = f.read()
201 if line != line2:
Fred Drakea63bd1c2000-12-13 20:23:11 +0000202 raise RuntimeError, 'bad result after seek back from EOF'
Barry Warsawc1401312000-12-12 23:16:51 +0000203 print 'Read', len(list), 'more lines'
204 print 'File length =', f.tell()
205 if f.tell() != length:
Fred Drakea63bd1c2000-12-13 20:23:11 +0000206 raise RuntimeError, 'bad length'
Barry Warsawc1401312000-12-12 23:16:51 +0000207 f.close()
Guido van Rossum85d89451994-06-23 11:53:27 +0000208
209if __name__ == '__main__':
Barry Warsawc1401312000-12-12 23:16:51 +0000210 test()