ยปCore Development>Code coverage>Lib/StringIO.py

Python code coverage for Lib/StringIO.py

#countcontent
1n/ar"""File-like objects that read from or write to a string buffer.
2n/a
3n/aThis implements (nearly) all stdio methods.
4n/a
5n/af = StringIO() # ready for writing
6n/af = StringIO(buf) # ready for reading
7n/af.close() # explicitly release resources held
8n/aflag = f.isatty() # always false
9n/apos = f.tell() # get current position
10n/af.seek(pos) # set current position
11n/af.seek(pos, mode) # mode 0: absolute; 1: relative; 2: relative to EOF
12n/abuf = f.read() # read until EOF
13n/abuf = f.read(n) # read up to n bytes
14n/abuf = f.readline() # read until end of line ('\n') or EOF
15n/alist = f.readlines()# list of f.readline() results until EOF
16n/af.truncate([size]) # truncate file at to at most size (default: current pos)
17n/af.write(buf) # write at current position
18n/af.writelines(list) # for line in list: f.write(line)
19n/af.getvalue() # return whole file's contents as a string
20n/a
21n/aNotes:
22n/a- Using a real file is often faster (but less convenient).
23n/a- There's also a much faster implementation in C, called cStringIO, but
24n/a it's not subclassable.
25n/a- fileno() is left unimplemented so that code which uses it triggers
26n/a an exception early.
27n/a- Seeking far beyond EOF and then writing will insert real null
28n/a bytes that occupy space in the buffer.
29n/a- There's a simple test set (see end of this file).
30n/a"""
310try:
320 from errno import EINVAL
330except ImportError:
340 EINVAL = 22
35n/a
360__all__ = ["StringIO"]
37n/a
380def _complain_ifclosed(closed):
39510300 if closed:
406 raise ValueError, "I/O operation on closed file"
41n/a
420class StringIO:
43n/a """class StringIO([buffer])
44n/a
45n/a When a StringIO object is created, it can be initialized to an existing
46n/a string by passing the string to the constructor. If no string is given,
47n/a the StringIO will start empty.
48n/a
49n/a The StringIO object can accept either Unicode or 8-bit strings, but
50n/a mixing the two may take some care. If both are used, 8-bit strings that
51n/a cannot be interpreted as 7-bit ASCII (that use the 8th bit) will cause
52n/a a UnicodeError to be raised when getvalue() is called.
53n/a """
540 def __init__(self, buf = ''):
55n/a # Force self.buf to be a string or unicode
5647437 if not isinstance(buf, basestring):
5710 buf = str(buf)
5847437 self.buf = buf
5947437 self.len = len(buf)
6047437 self.buflist = []
6147437 self.pos = 0
6247437 self.closed = False
6347437 self.softspace = 0
64n/a
650 def __iter__(self):
664 return self
67n/a
680 def next(self):
69n/a """A file object is its own iterator, for example iter(f) returns f
70n/a (unless f is closed). When a file is used as an iterator, typically
71n/a in a for loop (for example, for line in f: print line), the next()
72n/a method is called repeatedly. This method returns the next input line,
73n/a or raises StopIteration when EOF is hit.
74n/a """
7514 _complain_ifclosed(self.closed)
7612 r = self.readline()
7712 if not r:
782 raise StopIteration
7910 return r
80n/a
810 def close(self):
82n/a """Free the memory buffer.
83n/a """
8438 if not self.closed:
8537 self.closed = True
8637 del self.buf, self.pos
87n/a
880 def isatty(self):
89n/a """Returns False because StringIO objects are not connected to a
90n/a tty-like device.
91n/a """
924 _complain_ifclosed(self.closed)
932 return False
94n/a
950 def seek(self, pos, mode = 0):
96n/a """Set the file's current position.
97n/a
98n/a The mode argument is optional and defaults to 0 (absolute file
99n/a positioning); other values are 1 (seek relative to the current
100n/a position) and 2 (seek relative to the file's end).
101n/a
102n/a There is no return value.
103n/a """
1041773 _complain_ifclosed(self.closed)
1051773 if self.buflist:
106261 self.buf += ''.join(self.buflist)
107261 self.buflist = []
1081773 if mode == 1:
1090 pos += self.pos
1101773 elif mode == 2:
111212 pos += self.len
1121773 self.pos = max(0, pos)
113n/a
1140 def tell(self):
115n/a """Return the file's current position."""
1161814 _complain_ifclosed(self.closed)
1171814 return self.pos
118n/a
1190 def read(self, n = -1):
120n/a """Read at most size bytes from the file
121n/a (less if the read hits EOF before obtaining size bytes).
122n/a
123n/a If the size argument is negative or omitted, read all data until EOF
124n/a is reached. The bytes are returned as a string object. An empty
125n/a string is returned when EOF is encountered immediately.
126n/a """
127229187 _complain_ifclosed(self.closed)
128229187 if self.buflist:
1290 self.buf += ''.join(self.buflist)
1300 self.buflist = []
131229187 if n is None or n < 0:
1321346 newpos = self.len
133n/a else:
134227841 newpos = min(self.pos+n, self.len)
135229187 r = self.buf[self.pos:newpos]
136229187 self.pos = newpos
137229187 return r
138n/a
1390 def readline(self, length=None):
140n/a r"""Read one entire line from the file.
141n/a
142n/a A trailing newline character is kept in the string (but may be absent
143n/a when a file ends with an incomplete line). If the size argument is
144n/a present and non-negative, it is a maximum byte count (including the
145n/a trailing newline) and an incomplete line may be returned.
146n/a
147n/a An empty string is returned only when EOF is encountered immediately.
148n/a
149n/a Note: Unlike stdio's fgets(), the returned string contains null
150n/a characters ('\0') if they occurred in the input.
151n/a """
15241973 _complain_ifclosed(self.closed)
15341973 if self.buflist:
1544 self.buf += ''.join(self.buflist)
1554 self.buflist = []
15641973 i = self.buf.find('\n', self.pos)
15741973 if i < 0:
1581085 newpos = self.len
159n/a else:
16040888 newpos = i+1
16141973 if length is not None and length > 0:
16232977 if self.pos + length < newpos:
16328500 newpos = self.pos + length
16441973 r = self.buf[self.pos:newpos]
16541973 self.pos = newpos
16641973 return r
167n/a
1680 def readlines(self, sizehint = 0):
169n/a """Read until EOF using readline() and return a list containing the
170n/a lines thus read.
171n/a
172n/a If the optional sizehint argument is present, instead of reading up
173n/a to EOF, whole lines totalling approximately sizehint bytes (or more
174n/a to accommodate a final whole line).
175n/a """
17646 total = 0
17746 lines = []
17846 line = self.readline()
179356 while line:
180313 lines.append(line)
181313 total += len(line)
182313 if 0 < sizehint <= total:
1833 break
184310 line = self.readline()
18546 return lines
186n/a
1870 def truncate(self, size=None):
188n/a """Truncate the file's size.
189n/a
190n/a If the optional size argument is present, the file is truncated to
191n/a (at most) that size. The size defaults to the current position.
192n/a The current file position is not changed unless the position
193n/a is beyond the new file size.
194n/a
195n/a If the specified size exceeds the file's current size, the
196n/a file remains unchanged.
197n/a """
1984274 _complain_ifclosed(self.closed)
1994274 if size is None:
20014 size = self.pos
2014260 elif size < 0:
2022 raise IOError(EINVAL, "Negative size not allowed")
2034258 elif size < self.pos:
2042214 self.pos = size
2054272 self.buf = self.getvalue()[:size]
2064272 self.len = size
207n/a
2080 def write(self, s):
209n/a """Write a string to the file.
210n/a
211n/a There is no return value.
212n/a """
213230539 _complain_ifclosed(self.closed)
214230537 if not s: return
215n/a # Force s to be a string or unicode
216226842 if not isinstance(s, basestring):
2171 s = str(s)
218226842 spos = self.pos
219226842 slen = self.len
220226842 if spos == slen:
221226763 self.buflist.append(s)
222226763 self.len = self.pos = spos + len(s)
223226763 return
22479 if spos > slen:
2250 self.buflist.append('\0'*(spos - slen))
2260 slen = spos
22779 newpos = spos + len(s)
22879 if spos < slen:
22979 if self.buflist:
2303 self.buf += ''.join(self.buflist)
23179 self.buflist = [self.buf[:spos], s, self.buf[newpos:]]
23279 self.buf = ''
23379 if newpos > slen:
2345 slen = newpos
235n/a else:
2360 self.buflist.append(s)
2370 slen = newpos
23879 self.len = slen
23979 self.pos = newpos
240n/a
2410 def writelines(self, iterable):
242n/a """Write a sequence of strings to the file. The sequence can be any
243n/a iterable object producing strings, typically a list of strings. There
244n/a is no return value.
245n/a
246n/a (The name is intended to match readlines(); writelines() does not add
247n/a line separators.)
248n/a """
24915 write = self.write
25061 for line in iterable:
25146 write(line)
252n/a
2530 def flush(self):
254n/a """Flush the internal buffer
255n/a """
256722 _complain_ifclosed(self.closed)
257n/a
2580 def getvalue(self):
259n/a """
260n/a Retrieve the entire contents of the "file" at any time before
261n/a the StringIO object's close() method is called.
262n/a
263n/a The StringIO object can accept either Unicode or 8-bit strings,
264n/a but mixing the two may take some care. If both are used, 8-bit
265n/a strings that cannot be interpreted as 7-bit ASCII (that use the
266n/a 8th bit) will cause a UnicodeError to be raised when getvalue()
267n/a is called.
268n/a """
26918526 if self.buflist:
2709916 self.buf += ''.join(self.buflist)
2719916 self.buflist = []
27218526 return self.buf
273n/a
274n/a
275n/a# A little test suite
276n/a
2770def test():
2780 import sys
2790 if sys.argv[1:]:
2800 file = sys.argv[1]
281n/a else:
2820 file = '/etc/passwd'
2830 lines = open(file, 'r').readlines()
2840 text = open(file, 'r').read()
2850 f = StringIO()
2860 for line in lines[:-2]:
2870 f.write(line)
2880 f.writelines(lines[-2:])
2890 if f.getvalue() != text:
2900 raise RuntimeError, 'write failed'
2910 length = f.tell()
2920 print 'File length =', length
2930 f.seek(len(lines[0]))
2940 f.write(lines[1])
2950 f.seek(0)
2960 print 'First line =', repr(f.readline())
2970 print 'Position =', f.tell()
2980 line = f.readline()
2990 print 'Second line =', repr(line)
3000 f.seek(-len(line), 1)
3010 line2 = f.read(len(line))
3020 if line != line2:
3030 raise RuntimeError, 'bad result after seek back'
3040 f.seek(len(line2), 1)
3050 list = f.readlines()
3060 line = list[-1]
3070 f.seek(f.tell() - len(line))
3080 line2 = f.read()
3090 if line != line2:
3100 raise RuntimeError, 'bad result after seek back from EOF'
3110 print 'Read', len(list), 'more lines'
3120 print 'File length =', f.tell()
3130 if f.tell() != length:
3140 raise RuntimeError, 'bad length'
3150 f.truncate(length/2)
3160 f.seek(0, 2)
3170 print 'Truncated length =', f.tell()
3180 if f.tell() != length/2:
3190 raise RuntimeError, 'truncate did not adjust length'
3200 f.close()
321n/a
3220if __name__ == '__main__':
3230 test()